Tuesday, April 26, 2016

Notes about using Promises

Record some pitfalls when using Promises


1. Avoid directly accessing iterator in for-loop

In the above code, you'll probably see something  in the console output like
2 3 4 5 5 instead of 1 2 3 4 5 which is expected.

The reason of failure is that when somePromise is resolved and console.log(ary[i]) is about to executed, the value of i could be incremented already.

To access the right element in each iteration in the asynchronous function, my solution is to use IIFE to catch and pass element at the moment.

PS. This fix let you correctly access each element in the array but not guaranteed in the order of original array. i.e. you may see 1 3 2 4 5.
Because the resolved timing of each somePromise in the loop is asynchronous against iteration.


No comments:

Post a Comment