search

Home  >  Q&A  >  body text

node.js - Solve the sample code of Generator+Promise in JavaScript that you don’t know

function foo(x,y) {
    return request(
        //request是一个Promise对象
        "http://some.url.1/?x=" + x + "&y=" + y
    );
}

function *main() {
    try{
        var text = yield foo( 11, 31 );
        //在yield处暂停后 yield需要等待第二次next()传值 text应该没有被赋值
        console.log( text );
    }
    catch (err) {
        console.error( err );
    }
}

var it = main();

var p = it.next().value;
//等待promise p决议
p.then(
    function (text) {
        it.next( text );
        //这里拿到的 text 应该没有赋到值呀
    },
    
    function (err) {
        it.throw( err );
    }
);

这是你不知道的JavaScript 生成器+Promise 小节中的一段示例代码
**其中 text 应该拿到的是yield 的值 而yield 应该需要第二个next()去赋值 那么 text应该是undefined 这里我就看不懂了 求解!**
某草草某草草2801 days ago681

reply all(2)I'll reply

  • ringa_lee

    ringa_lee2017-06-15 09:23:42

    The next call of the first iterator will be executed to the first yield. At this time, no value is assigned, but an ajax function based on promise is returned.
    After resolution of this promise, the return value of the ajax request will be used as a parameter. The form is assigned to the first function in then as a parameter
    like this

    (() => new Promise((resolve => { resolve("我是参数"); })))().then(data => console.log(data), err => { throw err; })    //"我是参数"

    Next, this parameter will be assigned to the position of the first yield and the function will be executed

    reply
    0
  • 天蓬老师

    天蓬老师2017-06-15 09:23:42

    //The text obtained here should not be assigned a value

    I misunderstood, text is the result of successful request, I suggest you understand Promise again

    reply
    0
  • Cancelreply