Is it possible to wrap promise inside generator?

我怕爱的太早我们不能终老 提交于 2019-12-04 05:11:23
Bergi

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.

Would this approach work for you http://davidwalsh.name/async-generators ?

A modified example from the 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

You should probably read the entirety of that post, the runGenerator is a pretty neat approach.

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 );
            }
        })
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!