是否可以将 promise 包装在生成器中?

Is it possible to wrap promise inside generator?

我正在尝试使用生成器创建一个 promise-wrapper,以便我可以:

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

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

来自 link 的修改示例:

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

您可能应该完整阅读 post,runGenerator 是一个非常巧妙的方法。

在同步产生承诺结果的生成器中包装承诺是完全不可能的,因为承诺总是异步的。没有解决方法,除非你向异步投掷更强大的武器,如光纤。

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 );
            }
        })