Last active
November 19, 2018 23:18
-
-
Save wahyudibo/2c5ca4e02326e225329b0bdbd025b25e to your computer and use it in GitHub Desktop.
How to handle Promise fail fast behavior. Credits goes to : https://nmaggioni.xyz/2016/10/13/Avoiding-Promise-all-fail-fast-behavior/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let p1 = new Promise((resolve, reject) => { | |
setTimeout(resolve, 1000, "Everything OK in Promise 1"); | |
}); | |
let p2 = new Promise((resolve, reject) => { | |
reject(new Error("Something went wrong in Promise 2!")); | |
}); | |
let p3 = new Promise((resolve, reject) => { | |
setTimeout(resolve, 2000, "Everything OK in Promise 3"); | |
}); | |
const toResultObject = (promise) => { | |
return promise | |
.then(result => ({ success: true, result })) | |
.catch(error => ({ success: false, error })); | |
}; | |
Promise.all([p1, p2, p3].map(toResultObject)).then((values) => { | |
for (let i = 0; i < values.length; ++i) { | |
if (!values[i].success) { | |
console.log("ERR " + values[i].error); | |
} else { | |
console.log(values[i].result); | |
} | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment