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?