简体   繁体   中英

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. 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:

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:

let accessToken = yield storakleShopifyApi.exchangeTemporaryToken(parameters);

the storakleShopifyApi.exchangeTemporaryToken is another generator function which interestingly enough returns a 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?

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:

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)."

So it is Koa that is the glue between yield and promises.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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