[英]how to get the return value of an async function after then is called on the async function
Promises 看起来真的很简单。 但是每次遇到它,我都必须做一些解决方法,而实际上我只想同步执行一个函数。
我想知道我是否以某种方式错过了如何正确完成它,因为它应该如何工作似乎很明显。
想象一下下面的代码
getData()
.then(data => {
const dates = [];
generateDates(30, new Date(), dates)
.then(result => {
console.log(result)
})
})
generateDates() 的承诺在日期数组完成填充之前解决,因此 console.log() 返回 undefined。
为什么在函数返回之前调用 generateDates() 上的 then()? 该函数应该只在日期数组完全填充后返回。 Promise 对我来说没有意义。
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);
}
问题不在于在日期完成填充之前解决了 generateDates,而是因为没有返回递归调用。
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)) })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.