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

No comments:

Post a Comment