Getting a promise's value via yield & co

Mark Kahn picture Mark Kahn · Feb 18, 2014 · Viewed 11.8k times · Source

I'm trying to figure out how to get the value of a promise via yield, possibly with "co":

function *(){
    var someVar = yield functionThatReturnsAPromise();
}

The called function is not a generator, just a normal function. With the above, someVar == Promise, but I want the resolved value. Does co or some other library have a way of doing this?

Answer

Klaster_1 picture Klaster_1 · Feb 18, 2014

Yes, co can do that. You'll have to wrap parent function inside co call:

co(function *(){
    var someVar = yield functionThatReturnsAPromise();
})()

someVar inside will become resolved value. If promise gets rejected, error can be cought with basic try {} catch (e) {} statements.