promise.all for one promise code example
Example 1: javascript promise.all
try {
const [res1, res2, res3] = await Promise.all([
Promise1,
Promise2,
Promise3,
]);
} catch (err) {
console.error(err);
}
Example 2: promise all
Promise.all([Promise1, Promise2, Promise3])
.then(result) => {
console.log(result)
})
.catch(error => console.log(`Error in promises ${error}`))
Example 3: Promise.all
const promise1 = Promise.resolve(3);
const promise2 = 42;
const promise3 = new Promise(function(resolve, reject) {
setTimeout(resolve, 100, 'foo');
});
Promise.all([promise1, promise2, promise3]).then(function(values) {
console.log(values);
});
Example 4: javascript promise.all
async function fetchMoviesAndCategories() {
const [moviesResponse, categoriesResponse] = await Promise.all([
fetch('/movies'),
fetch('/categories')
]);
const movies = await moviesResponse.json();
const categories = await categoriesResponse.json();
return [movies, categories];
}
Example 5: promise all in promise all
var arr = [
{subarr: [1,2,3]},
{subarr: [4,5,6]},
{subarr: [7,8,9]}
];
function processAsync(n) {
return new Promise(function(resolve) {
setTimeout(
function() { resolve(n * n); },
Math.random() * 1e3
);
});
}
Promise.all(arr.map(function(entity){
return Promise.all(entity.subarr.map(function(item){
return processAsync(item);
}));
})).then(function(data) {
console.log(data);
});