简体   繁体   中英

How to wait for all .then are finished before returning value

I have the following function

const getQuotes = symbol => {
  let quotes = {};
  new DeltaRestClient(api_key, api_secret).then(client => {
    const linkOptions = createIdentifiers(symbol, false);
    Object.entries(linkOptions).forEach(entry => {
      client.apis.Products.getTicker({ symbol: entry[1] }).then(response => {
        const ticker = JSON.parse(response.data.toString());
        quotes[entry[0]] = parseFloat(ticker.result.close);
      });
    });
  });
  return quotes;
};

which I call in

const start = async () => {
  const quotes = await getQuotes("ABCD");
  console.log(quotes);
};

But because of the asynchronicity, getQuotes returns before all the .then are resolved and an empty object is returned.

How can I change this such that the value is only returned if all .then are resolved?

You have to await in the function you are calling too:

const getQuotes = async symbol => {
  let quotes = {};
  const client = await new DeltaRestClient(api_key, api_secret);
  const linkOptions = createIdentifiers(symbol, false);

  for (const entry of Object.entries(linkOptions)) {
      const response = await client.apis.Products.getTicker({ symbol: entry[1] });
      const ticker = JSON.parse(response.data.toString());
      quotes[entry[0]] = parseFloat(ticker.result.close);
  }
  return quotes;
};

And call it accordingly:

const start = async () => {
  const quotes = await getQuotes("ABCD");
  console.log(quotes);
};

Generelly mixing async/await and Promise.then/.catch leads to shady code that is easily misunderstood.

And if you like, you can increase readability by destructuring the entry element:

  for (const [key, symbol] of Object.entries(linkOptions)) {
      const response = await client.apis.Products.getTicker({ symbol, });
      const ticker = JSON.parse(response.data.toString());
      quotes[key] = parseFloat(ticker.result.close);
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM