我一直在到处搜索关于promise或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被定义为全局变量。)但是,就像我的代码正在以随机顺序执行一样……
答案 0 :(得分:4)
您的函数未返回任何内容。如果您希望它返回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 => {
// ...
});
答案 1 :(得分:2)
在下面查找: 工作示例jsFiddle
let currentDate;
const url = 'https://jsonplaceholder.typicode.com/posts/1';
function getMaxDate() {
return new Promise(resolve => {
fetch(url).then(data => {
return data.json();
}).then(json => {
console.log('data from api', json);
currentDate = new Date(); // here I simulate to get Date
console.log(currentDate);
resolve(currentDate);
}).catch(error => {
console.error('There was an error:');
console.log(e);
reject(error);
});
})
}
function getMarket(date) {
return new Promise(resolve => {
resolve({
market: 'US',
date
});
});
}
async function getAllData() {
try {
let currentDate = await getMaxDate();
console.log('getAllData', currentDate);
return await getMarket(currentDate);
} catch (error) {
console.log('An error occurred.');
}
}
// This function is called when the document is first loaded
$(function () {
getAllData().
then(result => {
console.log('do sth...', result);
});
});