Search code examples
javascriptes6-promise

How do I resolve nested promises in an object


Code:

async function main() {
  const arr = [];
  symbols.forEach((symbol) => {
    const record = {
      [symbol]: {
        quote: priceQuote(token, symbol),
        history: makePriceHistoryRequest(token, symbol, slow * 2),
      }
    }
    arr.push(record);
  })
    return arr;
}

I call main as follows:

main().then(res=>{
  console.log(res);
})

It returns quote and history as Promise. How can I get into nested pending promise?

Thanks!


Solution

  • If quote and history are promises it means that priceQuote and makePriceHistoryRequest are functions that return promises, in this case, you need to make the callback that iterates them async, not the wrapper:

     function main() {
       return Promise.all(symbols.map(async (symbol) => {
         const record = {
          [symbol]: {
            quote: await priceQuote(token, symbol),
            history: await makePriceHistoryRequest(token, symbol, slow * 2),
          }
        }
        return record
      })  
    }
    
    main().then(value => console.log(value) )