How to use multiple languages

Asked

Viewed 55 times

1

I don’t have much experience with Node.js, and I needed to generate several signed links, I have this block of code that works well.

bucket.file("test_users/xxxxx/avatar/thumbnail.jpeg")
        .getSignedUrl(options)
        .then(results => {
            const url = results[0];
            res.send(url);
            return true
        }).catch( err => {
            console.log("error generating signed url", err);
            return false
        })

Having a list of the various user ids, how can I create a list of links?

  • How would these "diverse" Promises look? They vary according to the "xxxx" in the URL?

1 answer

1


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(/* ... */);
  • Thank you so much for the detailed answer!! That’s just what I needed!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.