You can use the Promise.all
, that solves a list of promises simultaneously. Thus, a final promise will be returned as soon as all those passed are resolved.
An example:
// Nossa função que retorna uma promessa:
function getUserName(username) {
return fetch(`https://api.github.com/users/${username}`)
.then((response) => response.json())
.then((data) => data.name);
}
// Lista de usuários:
const users = ['gaearon', 'sindresorhus', 'tj', 'mdo'];
// Criamos uma lista de promessas a partir da nossa
// lista de usuários. Note que todas elas chamam a
// função `getUserName`, que retorna uma promessa.
const promises = users.map((username) => getUserName(username));
// Executamos todas as promessas:
Promise.all(promises)
.then((list) => console.log(list))
.catch((err) => console.error(err));
As you may have seen, we used the Array.prototype.map
as a way to map an array of values (a list of user names) into a list of promises, which will all be resolved by Promise.all
.
So the following two codes are equivalent:
Promise.all(
['gaearon', 'sindresorhus', 'tj', 'mdo']
.map((username) => getUserName(username))
)
.then(/* ... */)
.catch(/* ... */);
Promise.all([
getUserName('gaearon'),
getUserName('sindresorhus'),
getUserName('tj'),
getUserName('mdo')
])
.then(/* ... */)
.catch(/* ... */);
How would these "diverse" Promises look? They vary according to the "xxxx" in the URL?
– Luiz Felipe