promise-join-ext
v1.0.2
Published
Promise Extensions
Downloads
3
Maintainers
Readme
Promise.waitForAll
Promise.waitForAll
works much like Promise.all
. Promise.waitForAll will always resolve, even if some of the promises in the the array rejects.
Example
Promise.waitForAll([Promise.resolve('data'), Promise.reject('error')])
.then(results => {
console.log(results.length) //2
console.log(results[0].status) //success
console.log(results[0].result) //data
console.log(results[1].status) //failure
console.log(results[1].error) //error
}).catch(() => {
//Dead code;
});
Validating promise result
import PromiseExt from 'promiseExt'
...
const isSuccessful = results[0].status === PromiseExt.status.SUCCESS;
const didFail = results[0].status === PromiseExt.status.FAILURE;
Promise.joinPooledTasks
Promise.joinPooledTasks
will run a list of tasks, while making sure only n of them will execute at the same time. It will resolve when all tasks are done and like Promise.waitForAll
will never reject. The concept is much like a threading pool.
Example
//Define a taskProvider. index is the task index, running from 0 to taskCount;
//When there are no tasks left, null should be returned.
const taskProvider = index => {
const taskCount = 20;
if (index > taskCount) return null;
return new Promise((resolve, reject) => {
setTimeout(() => {
if (Math.random() > 0.5) {
resolve(index)
} else {
reject(index);
}
}, 1000);
});
};
const progressCallback = (result) => {
console.log(`task #${result.index}: ${result.status}: ${result.status === "success" ? result.result : result.error}`)
};
const poolSize = 3;
Promise.joinPooledTasks(taskProvider, poolSize, progressCallback)
.then(results => {
console.log(`${results.length} promises ended`);
for (let i = 0; i < results.length; i++) {
const result = results[i];
if (result.status === "success") {
console.log(`${i} >> success: ${result.result}`);
} else {
console.log(`${i} >> failure: ${result.error}`);
}
}
}, err => {
//Dead code;
});
Alternative method of invocation
the package adds both its method to the Promise
prototype. you can invoke the methods directly:
import PromiseExt from 'promiseExt'
PromiseExt.waitForAll(...);
PromiseExt.joinPooledTasks(...);