The function description
This function works like promise. all, except that the promises in Promise.all are parallel, and the promises in this function are executed in sequence, like this
function async fun(arr){
const results = [];
await arr[0];
await arr[1];
await arr[2]; .// Returns an array of all promise results
return results;
}
Copy the code
implementation
All we know for sure is that this function takes an array and returns a promise. To implement serialization, the elements of the array cannot be promises, but should be functions that return promises, since promises run once they are created.
//promise serial function
function serialPromises(arr=[]) {
const result = [];
return new Promise((resolve, reject) = > {
resolve(result)
});
}
// The return value is the promise function
function promiseCreator(time){
return new Promise((resolve, reject) = > {
settimeout(() = >{
resolve(time)
}, time*1000)})}// An example
const arr = [
promiseCreator.bind(null.1),
promiseCreator.bind(null.3),
promiseCreator.bind(null.5),
promiseCreator.bind(null.4),
promiseCreator.bind(null.2)]; serialPromises(arr).then(console.log).catch(console.error);
Copy the code
Next, improve the function body of Series Promises. The idea is that the then function of the current promise always calls the next promiseCreator until the last promise.
function serialPromises(arr=[]) {
// The result array for promise
const result = [];
const arrLength = arr.length;
return new Promise((resolve, reject) = > {
let index = 1;
//then callback function, which implements the call to promise in turn
function resolvePromise(v) {
result.push(v);
// Not the last one
if (index + 1 < arrLength) {
// Call the function at index to generate the next promise
arr[index++]().then(resolvePromise);
} else {
// Resolve returns the promise after the last promise completes
arr[index]().then((v) = > {
result.push(v);
resolve(result);
}).catch((err) = >{ reject(err); }); }}if (arrLength === 0) {
resolve(result)
} else {
// Trigger the first promise
arr[0]().then(resolvePromise); }}); }Copy the code
Test the
function promiseCreator(time){
return new Promise((resolve, reject) = > {
setTimeout(() = >{
resolve(time)
}, time*1000)})}const arr = [
promiseCreator.bind(null.1),
promiseCreator.bind(null.3),
promiseCreator.bind(null.5),
promiseCreator.bind(null.4),
promiseCreator.bind(null.2)]; serialPromises(arr).then(console.log).catch(console.error);Print [1,3,5,4,2] after about 15 seconds
Copy the code