paint-brush
[ Javascript ] Killer of Sequential Promisesby@peterchang_82818
1,434 reads
1,434 reads

[ Javascript ] Killer of Sequential Promises

by December 3rd, 2016
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

However, a use case that chain N unknown number of promises with parameters and resolving them sequentially, it seem like impossible to accomplish by either native ES6 Promises or by third party libraries: q, bluebird, deferred.js etc.

Coin Mentioned

Mention Thumbnail
featured image - [ Javascript ] Killer of Sequential Promises
 HackerNoon profile picture

The pain of javascript is fighting with async functions, specially the big boss “CALLBACK HELL”, when you putting thousand console.log to make the code dirty to kill one CALLBACK bug. It lasted for long until I found Promises, which follows simple logical, organized resolve-reject structure and it solves most of the async problems, so thank you to Promises.

However, a use case that chain N unknown number of promises with parameters and resolving them sequentially, it seem like impossible to accomplish by either native ES6 Promises or by third party libraries: q, bluebird, deferred.js etc.

Failed example:

Defining genPromist function which will be used many times in this article:








var genPromist = function(para) {return new Promise(function(resolve, reject) {setTimeout(function() {console.log('para: ', para)resolve(para * para)}, 1000)})}

Chain 4 promises and resolve it recursively:




var promises = [];promises.push(genPromist(1));promises.push(genPromist(2));promises.push(genPromist(3));












var recursiveFunction = function(promisesList) {return new Promise(function(resolve, reject) {if (promisesList.length <= 0) {resolve()} else {return promisesList[0].then(function() {promisesList.shift();return recursiveFunction(promisesList);});}});}

recursiveFunction(promises)

Sadly, the program did not run as expected, and the promises array was resolved parallelly. And most of the libraries works well when promise function has no parameter, which means that a CLASS in javascript.

Solution:

The ways Javascript handling functions of promises and functions of promises with parameters are different ( issue of anonymous function with parameters ).

So that handling this issue needed to push promise function (not a promise) to an array list

PACU is a tool to solve the problem of chaining promises functions with parameters and resolving each continuously.

Installation:

$ npm install --save pacu

Usage:

var pacu = require("pacu")

pacu.series(promisesList).then(function(result) {

console.log("Result series: ", result)

},function(err){

console.log("Error series: ", result)

});