Monday, March 27, 2017

Javascript asynchronous and promise

The javascript is now using lots of asynchronous call.  In some scenarios, you need an asynchronous call chain, one after another. Promise can help on asynchronous chain.

Here is the requirement. 
The UI display a task list. Each task has a priority, which determines the display order on the UI.
There is up arrow and down arrow on the right of each task. Clicking the up arrow will exchange the priority with the task above.

The code here is nodejs and mongoose. 
Here is the pseudo code. 
//find current task by taskId
//find the previous task based on the current task priority
//exchange the priority
//save the tasks (update first task, once it is done, in the callback update the second task)
There are at least 4 callback functions embedded. The code is hard for reading.
With Promise, the code could be refactored like this. It is much neat and easy for reading.
For code "Task.findById(id)", Mongoose returns a promise.
Once the record is returned, the method then is executed. It calls the function "findThisAndPreviousTaskByPriority", which returns two records in an array.
the function then returns a promise as well. Once the inside function returns, it triggers the next "then", which is exchangePriority. It also returns an array contains two tasks, but their priorities have already been exchanged. "updateTwoTasksPriority" basically creates two mongoose update promise based on the two tasks. The last function call uses "Promise.all" to convert a promises Iterate into one single promise.

Here are some good articles about javascript promise
https://davidwalsh.name/promises
http://stackoverflow.com/questions/39028882/chaining-async-method-calls-javascript
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
https://www.youtube.com/watch?v=s6SH72uAn3Q
https://60devs.com/best-practices-for-using-promises-in-js.html
http://mongoosejs.com/docs/promises.html
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
http://stackoverflow.com/questions/22519784/how-do-i-convert-an-existing-callback-api-to-promises





No comments:

Post a Comment