7

我正在尝试使用生成器创建一个承诺包装器,以便我可以这样做:

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

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

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

但这失败了,因为不允许在法线内屈服。有什么解决方法吗?谢谢 :D

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

4

3 回答 3

6

将一个 Promise 包装在一个同步生成 Promise 结果的生成器中是完全不可能的,因为 Promise 总是异步的。没有解决方法,除非你在异步中扔出更强大的武器,比如纤维。

于 2015-04-28T08:14:07.553 回答
3

这种方法对你有用吗http://davidwalsh.name/async-generators

链接中的修改示例:

function wrap(promise) {
    promise.then(function(result){
        it.next( result );
    }, function(err){
        throw err;
    });
}

function *main() {
    var result1 = yield wrap( $.ajax( ... ) );
    var data = JSON.parse( result1 );
}

var it = main();
it.next(); // get it all started

您可能应该阅读该帖子的全部内容,这runGenerator是一种非常简洁的方法。

于 2015-04-28T07:49:57.807 回答
-1
function step1(){

    return new Promise(function(c,e){
         setTimeout(function(){
              c(`1000 spet 1`);
         },1000)
    })

}

function step2(){
    return new Promise(function(c,e){
        setTimeout(function(){
            c(`100 spet 2`);
        },10000)
    })
}


function step3(){
    return new Promise(function(c,e){
        setTimeout(function(){
            c(`3000 spet 3`);
        },3000)
    })
}


function step4(){
    return new Promise(function(c,e){
        setTimeout(function(){
            c(`100 spet 4`);
        },100)
    })
}



function *main() {
    var ret = yield step1();
    try {
        ret = yield step2( ret );
    }
    catch (err) {
        ret = yield step2Failed( err );
    }
    ret = yield Promise.all( [
        step3( ret )

    ] );

    yield step4( ret );
}

var it = main();

/*
while (true) {
    var current = it.next();
    if (current.done) break;
    console.log(current.value);
}
*/
Promise.all( [ ...it ] ) // Convert iterator to an array or yielded promises.
    .then(
        function handleResolve( lines ) {

            for ( var line of lines ) {
                console.log( line );
            }
        })
于 2017-09-24T05:57:25.883 回答