create a function called promisified, which return a promise.
in the promise initialize function, we push a callback function into the arguments into promisified and use the new arguments to call callbackBasedApi, in the callback we pushed into arguments, it use resolve and reject to fullfill a the promise.
Sequential Iteration
1
2
3
4
5
6
7
8
9
10
let tasks = [ /* ... */ ]
let promise = Promise.resolve();
tasks.forEach(task => {
promise = promise.then(() => {
return task();
});
});
promise.then(() => {
//All tasks completed
});
or instead of forEach, use reduce.
1
2
3
4
5
6
7
8
9
10
11
let tasks = [ /* ... */ ]
let promise = tasks.reduce((prev, task) => {
return prev.then(() => {
return task();
});
}, Promise.resolve());
promise.then(() => {
//All tasks completed
});
Both use a Promise.resove() to kick the first iteration.