我一直在到处搜索有关 promises 或 async/await 的信息,但它们似乎不起作用。在我可以在后续函数中使用该日期之前,我需要从查询函数中获取当前日期。这是我目前为止最好的猜测:
// Retrieve current session date
var currentDate;
async function getMaxDate() {
fetch(url).then((data) => {
return data.json();
}).then((json) => {
// This is the date used in queries
currentDate = json[obj].max.substr(0, 10);
console.log(currentDate);
return new Promise(resolve => {
setTimeout(() => {
resolve(currentDate);
}, 5000);
});
}).catch((e) => {
console.error('There was an error:');
console.log(e);
});
}
async function getAllData() {
try {
currentDate = await getMaxDate();
await getMarket(currentDate);
console.log(currentDate);
} catch (error) {
console.log('An error occurred.');
}
}
// This function is called when the document is first loaded
$(function () {
let promise = getAllData();
});
但是不管有没有 promise/async/await,行为都是一样的——currentDate 直到几秒后才定义。我也试过这样调用:
getAllData()
.then(function (currentDate) {
console.log(currentDate);
});
这里的 currentDate 直到稍后仍未定义。为了进一步说明 - getMaxDate 执行的提取可能足够慢以导致此问题。因为在该函数的后面,console.log(currentDate) 确实输出了正确的值。 (currentDate 被定义为一个全局变量。)但它就像我的代码以随机顺序执行......
最佳答案
您的函数不返回任何内容。如果您希望它返回 currentDate
,您必须明确地这样做。
async function getAllData() {
try {
let currentDate = await getMaxDate();
await getMarket(currentDate);
console.log(currentDate);
return currentDate;
} catch (error) {
console.log('An error occurred.');
}
}
返回值将是在 then
情况或 await
情况下分配的值:
let currentDate = await getAllData();
getAllData.then(currentDate => {
// ...
});
关于javascript - 我们如何在 JavaScript 中等待结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52189402/