5

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?

John Slegers
  • 45,213
  • 22
  • 199
  • 169
Milen Kovachev
  • 5,111
  • 6
  • 41
  • 58
  • 1
    No, yield does not know anything about what it is yielding, whether a promise or anything else. But the consumer of the yield is the koa framework, which **does** know that the yielded value is a promise, waits for it to resolve, then passes the resulting value back to the generator in the next call to `next`, which has the effect of making it the "value" of the yield and thus assigned to `accessToken`. This behavior is at the heart of koa. –  Feb 19 '16 at 17:28

1 Answers1

2

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.

Milen Kovachev
  • 5,111
  • 6
  • 41
  • 58