Information about Promise
https://javascript.info/promise-basics
const f = (resolve, error) => {
if ( 2 > 1 ) {
resolve(12345)
}
}
const p = new Promise(f)
const dofinalstuff = () => console.log('Do final stuff')
const dosomething = (result) => console.log('Hello ' + result)
const doerror = (error) => console.log('error: ' + error)
p.finally(dofinalstuff).then(dosomething, doerror)
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
delay(3000).then(() => alert('runs after 3 seconds'));
new Promise((resolve, reject) => {
throw new Error("error");
})
.finally(() => alert("Promise ready")) // triggers first
.catch(err => alert(err)); // <-- .catch shows the error
Promise.race()
Promise.race() is used to handle multiple concurrent promises.
Promise.race() waits for only one promise to resolve or reject.
Promise.race([promise1, promise2, promise3])
.then(results => console.log(results))
.catch(error => console.log(error))
Promise.all()
Promise.all() waits until all the promises have completed.
// Promise.all) method is used to handle multiple promises concurrently.
const promisel = new Promise((resolve) => setTimeout(resolve, 1000, "Hello"));
const promise = new Promise ((resolve) => setTimeout(resolve, 2000, "World"));
const promise = new Promise((resolve) => setTimeout (resolve, 1500, "Happy"));
//
// Promise.all takes an array of promises as input and returns a new promise.
Promise.all([promise1, promise, promise31)
.then ((results) => {
console.log(results)
})
.catch ((error) => {
console. error ("Error:", error);
});
// Output: ['Hello', 'World", "Happy']