Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 541
Milen Kovachev Avatar asked Oct 31 '22 09:10

Milen Kovachev


1 Answers

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.

like image 75
Milen Kovachev Avatar answered Nov 14 '22 05:11

Milen Kovachev