背景:我需要在同步函数 getHolidaysByYear
中使用异步函数 isHoliday
的结果,因为同步函数是组件的一部分。但是异步函数比同步函数运行晚,如何在继续同步函数之前从异步函数中获取结果。
例子:
//Call rest to get range of holidays
async function getHolidaysByYear(year : number) : Date[] {
//I use other rest server to get range
let dates = await api.request(year);
if(dates !== undefined)
{
console.log("holidays : " + dates.length);
return dates;
}
else
{
return [];
}
}
//Function is used in component
function isHoliday(current : Moment) : booleant {
//other parts (cache and other parts)
let year : number = current.toDate().getFullYear();
let dates : Date[] = [];
console.log("before : " dates.length);
getHolidaysByYear(year).then(values => {dates = values});
console.log("after : " dates.length);
//other parts (cache and other parts) ...
}
现在我得到下一个控制台结果:
before : 0
after : 0
holidays : 143
但我想得到这样的东西:
before : 0
holidays : 143
after : 143
答案 0 :(得分:0)
您必须将“after”部分放在“then”块中,以确保“after”部分在 getHolidaysByYear
之后执行。
getHolidaysByYear(year)
.then(values => {
dates = values
console.log("after: ", dates.length)
// other parts
});
但是如果你不喜欢把所有其他的东西都放在 then 块里,你可以把 isHoliday 函数变成异步函数。
//Function is used in component
async function isHoliday(current : Moment) : boolean {
//other parts (cache and other parts)
let year : number = current.toDate().getFullYear();
let dates : Date[] = [];
console.log("before : " dates.length);
dates = await getHolidaysByYear(year)
console.log("after : " dates.length);
//other parts (cache and other parts) ...
}