简体   繁体   English

yield如何理解Node.js / Koa.js应用程序中的Promise?

[英]How does yield understand Promises in a Node.js/Koa.js application?

I am looking at a Koa.js/Node.js application and I think I have a good understanding of generators and promises. 我正在看一个Koa.js / Node.js应用程序,我想我对生成器和承诺有很好的理解。 But I cannot wrap my head around the following code: 但我不能围绕以下代码:

function *parseAuthorization() {
    let parameters = this.query;
    let accessToken = yield storakleShopifyApi.exchangeTemporaryToken(parameters);

    if(accessToken) {
        return ...
    }
    return this.response.redirect("/home/");
};

The exchangeTemporaryToken method is as follows: exchangeTemporaryToken方法如下:

function* exchangeTemporaryToken(query) {
    let authApi = getAuthApi(query.shop);
    return new Promise(function (resolve, reject) {
        authApi.exchange_temporary_token(query, function (err, data) {
            if (err) {
                return reject(err);
            }
            return resolve(data['access_token']);
        });
    });
};

*parseAuthorization is obviously a generator function (an API action in this case) which blocks on this line: * parseAuthorization显然是一个生成器函数(在这种情况下是一个API动作),它在这一行上阻塞:

let accessToken = yield storakleShopifyApi.exchangeTemporaryToken(parameters);

the storakleShopifyApi.exchangeTemporaryToken is another generator function which interestingly enough returns a Promise. storakleShopifyApi.exchangeTemporaryToken是另一个生成器函数,有趣的是返回一个Promise。

But yield by itself does not understand promises, does it? 但产量本身并不理解承诺,是吗? I am also assuming that the call to: 我也假设致电:

storakleShopifyApi.exchangeTemporaryToken(parameters);

Returns: 返回:

IteratorResult {value: Promise..., done: true}

So how does yield handle this and assigns the resolved value from the promise to the accessToken variable? 那么yield如何处理这个并将promise中的已解析值分配给accessToken变量?

I never thought that going beyond the 1st page of the Google search results had any value but I think I found the answer to my question there: 我从未想过超越Google搜索结果的第一页有任何价值,但我想我在那里找到了我的问题的答案:

http://blog.stevensanderson.com/2013/12/21/experiments-with-koa-and-javascript-generators/ http://blog.stevensanderson.com/2013/12/21/experiments-with-koa-and-javascript-generators/

Quoting from this post: 引用这篇文章:

"And that's how Koa works – your application code is the generator, it emits a series of promises (or other things I'll show below), and Koa waits for each one to complete before resuming your code (passing back to you the result of the previous task)." “这就是Koa的工作原理 - 你的应用程序代码是生成器,它会发出一系列的承诺(或者我将在下面展示的其他东西),Koa会在恢复你的代码之前等待每一个都完成(把结果传回给你)上一个任务)。“

So it is Koa that is the glue between yield and promises. 因此,Koa是产量和承诺之间的粘合剂。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM