How to understand the level of Promises in the Node.js / Koa.js app?

I am watching the Koa.js / Node.js application and I think I am well versed in generators and promises. But I can’t wrap my head in 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) that blocks on this line:

 let accessToken = yield storakleShopifyApi.exchangeTemporaryToken(parameters); 

the storakleShopifyApi.exchangeTemporaryToken is another generator function that returns Promise quite interestingly.

But the solution itself does not understand promises, does it? I also assume that the call:

 storakleShopifyApi.exchangeTemporaryToken(parameters); 

Return:

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

So how to do this by processing this and assigning the allowed value from the promise of the variable accessToken?

+5
source share
1 answer

I never thought that going beyond the first page of Google search results was of any value, but I think I found the answer to my question:

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

Quote from this post:

"And this is how Koa works - your application code is a generator, it emits a series of promises (or other things that are shown below), and Koa waits for each of them to complete before resuming your code (switching to you is the result of the previous task).

So this Koa is the glue between the crop and the promises.

+2
source

Source: https://habr.com/ru/post/1243412/


All Articles