Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to wrap promise inside generator?

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

like image 827
Dev Doomari Avatar asked Apr 28 '15 07:04

Dev Doomari


2 Answers

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.

like image 177
Bergi Avatar answered Sep 21 '22 23:09

Bergi


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.

like image 28
ekuusela Avatar answered Sep 19 '22 23:09

ekuusela