是否可能在发电机内包裹承诺? [英] Is it possible to wrap promise inside generator?

查看:126
本文介绍了是否可能在发电机内包裹承诺?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  var asyncResult = PromiseWrapper( $ .ajax(...)); 

到目前为止,我一直在尝试:

 函数PromiseWrapper(promise){
return function * wrapper(promise){
promise.then(function(result){
yield result ;
},function(err){
throw err;
});
}(promise).next()。value
}

但是失败,因为不允许在正常范围内产生。
有没有办法解决这个问题?谢谢你:D



ps:我用babel将代码从es6翻译成es5

解决方案

在同步产生承诺结果的生成器中包含承诺是绝对不可能的,因为承诺总是异步的。没有解决办法,除非你在异步时抛出更强大的武器,如纤维。


I'm trying to create a promise-wrapper using generator so that I can do:

var asyncResult = PromiseWrapper( $.ajax( ... ) );

So far, I've been trying with:

function PromiseWrapper(promise){
    return function *wrapper(promise){
        promise.then(function(result){
            yield result;
        }, function(err){
            throw err;
        });
    }(promise).next().value
}

but this fails because yielding inside a normal is not allowed. Is there any work-around for this? Thank you :D

ps: I'm using babel to translate the code from es6 to es5

解决方案

It is utterly impossible to wrap a promise in a generator that synchronously yields the promise's result, because promises are always asynchronous. There is no workaround for that, unless you throw mightier weapons like fibers at the asynchrony.

这篇关于是否可能在发电机内包裹承诺?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆