ECMA6 generators: promise

As I understand it, ECMA6 generators must be inferior to a function that returns a promise, ultimately returning allowed / rejected. Make code more like synchronous code and avoid callback addon.

I am using node.js v0.12.2 with --harmony and the following code.

var someAsyncThing = function() {
  return new Promise(function(resolve, reject) {
    resolve("I'm Resolved!");
  });
};

someAsyncThing().then(function(res) {console.log(res);});
// Works as expected: logs I'm Resolved!

function* getPromise() {
    var x = yield someAsyncThing();
    console.log("x: " + x); // Fails x undefined
}

var y = getPromise();
console.log(y); // returns {}

console.log(y.next());
// Fails: logs { value: {}, done: false }

I based the code on several examples that I managed to find on the Internet. What am I doing wrong?

+4
source share
2 answers

As I understand it, ECMA6 generators must be inferior to a function that returns a promise, ultimately returning allowed / rejected.

, . ES6 - . - - , .

, promises, . . promises.

, , promises . (, co task.js) , (Q, Bluebird, when,...), :

function run(gf) {
    let g = gf();
    return Promise.resolve(function step(v) {
         var res = g.next(v);
         if (res.done) return res.value;
         return res.value.then(step);
    }());
}

"" getPromise:

run(getPromise).then(console.log, console.error);
+3

tl; dr: .


http://davidwalsh.name/async-generators, , async :

function request(url) {
    // this is where we're hiding the asynchronicity,
    // away from the main code of our generator
    // `it.next(..)` is the generator iterator-resume
    // call
    makeAjaxCall( url, function(response){
        it.next( response );               // <--- this is where the magic happens
    } );
    // Note: nothing returned here!
}

promises, . y.next().value , . console.log(y.next()) :

var promise = y.next().value;
promise.then(y.next.bind(y)); // or promise.then(function(v) { y.next(v); });

Babel demo

, , , , . , . , runGenerator, , .

+2

Source: https://habr.com/ru/post/1589469/


All Articles