1var p1 = Promise.resolve(3);
2var p2 = 1337;
3var p3 = new Promise((resolve, reject) => {
4 setTimeout(resolve, 100, "foo");
5});
6
7Promise.all([p1, p2, p3]).then(values => {
8 console.log(values); // [3, 1337, "foo"]
9});
1const promise1 = Promise.resolve(3);
2const promise2 = 42;
3const promise3 = new Promise(function(resolve, reject) {
4 setTimeout(resolve, 100, 'foo');
5});
6
7Promise.all([promise1, promise2, promise3]).then(function(values) {
8 console.log(values);
9});
10// expected output: Array [3, 42, "foo"]
11
1const durations = [1000, 2000, 3000]
2
3promises = durations.map((duration) => {
4 return timeOut(duration).catch(e => e) // Handling the error for each promise.
5})
6
7Promise.all(promises)
8 .then(response => console.log(response)) // ["Completed in 1000", "Rejected in 2000", "Completed in 3000"]
9 .catch(error => console.log(`Error in executing ${error}`))
10view raw
1// A simple promise that resolves after a given time
2const timeOut = (t) => {
3 return new Promise((resolve, reject) => {
4 setTimeout(() => {
5 if (t === 2000) {
6 reject(`Rejected in ${t}`)
7 } else {
8 resolve(`Completed in ${t}`)
9 }
10 }, t)
11 })
12}
13
14const durations = [1000, 2000, 3000]
15
16const promises = []
17
18durations.map((duration) => {
19 promises.push(timeOut(duration))
20})
21
22// We are passing an array of pending promises to Promise.all
23Promise.all(promises)
24.then(response => console.log(response)) // Promise.all cannot be resolved, as one of the promises passed got rejected.
25.catch(error => console.log(`Error in executing ${error}`)) // Promise.all throws an error.
26
1var p1 = Promise.resolve(3);
2var p2 = 1337;
3var p3 = new Promise((resolve, reject) => {
4 setTimeout(() => {
5 resolve("foo");
6 }, 100);
7});
8
9Promise.all([p1, p2, p3]).then(values => {
10 console.log(values); // [3, 1337, "foo"]
11});
1// A simple promise that resolves after a given time
2const timeOut = (t) => {
3 return new Promise((resolve, reject) => {
4 setTimeout(() => {
5 resolve(`Completed in ${t}`)
6 }, t)
7 })
8}
9
10// Resolving a normal promise.
11timeOut(1000)
12 .then(result => console.log(result)) // Completed in 1000
13
14// Promise.all
15Promise.all([timeOut(1000), timeOut(2000)])
16 .then(result => console.log(result)) // ["Completed in 1000", "Completed in 2000"]