简体   繁体   中英

how to get the return value of an async function after then is called on the async function

Promises seem really straight forward. But every time I come across it, I have to do workarounds, when in fact I only want a function to be executed synchronously.

I'm wondering if I somehow missed how to do it properly because it seems so obvious how it should work.

Imagine the following code

getData()
.then(data => {
  const dates = [];
  generateDates(30, new Date(), dates)
  .then(result => {
    console.log(result)
  })
})

The promise of generateDates() is resolved before the dates array is finished populating, thus the console.log() returns undefined.

Why is then() on generateDates() called before the function returns? The function should only return once the dates array is completely populated. Promises don't make sense to me this way.

const generateDates = async(n, date, dates) => {
  if (n === 0) {
    return dates;
  }
  dates.push(date);
  n--;
  date = date - (30 * 24 * 60 * 60 * 1000)
  generateDates(n, date, dates);
}

The issue is not that generateDates is been resolved before the dates finish populating, it because the recursive call is not been returned.

 const getData = async() => {}; const generateDates = async(n, date, dates) => { if (n === 0) { return dates; } dates.push(date); n--; date = date - (30 * 24 * 60 * 60 * 1000) return generateDates(n, date, dates); } const dates = []; getData().then(data => { const dates = []; generateDates(2, new Date(), dates).then(result => console.log(result)) })

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