我正在用async和await学习javascript,并自己尝试了一些示例,但是似乎从另一个函数(func2)调用异步函数(func1)时,func2并不等待func1完成其过程,并且会跳转结束并继续执行...我的代码有什么问题吗?还是我也应该将func2转换为async并在等待状态下调用func1?如果是这样,这是否意味着将涉及async-await方法的所有功能也都需要变为异步状态? 这是我的原始代码
// func1
const func1 = async() => {
try {
await putCallToServer(...);
return 1; // it returns as a promise
} catch(ex) {
return 2;
}
}
// func2
const func2 = () => {
let result = 0;
result = func1(); // should I turn it into await func1()??
console.log(result); // log contains '0' instead of '1' or '2'
return result; // return as Promise but value inside is 0
}
如果我有一个称为func2的func3,我也应该将func3转换为async-await吗?
答案 0 :(得分:3)
如注释中所述,两个函数必须异步才能使用await。可以在下面的代码片段中看到。 (由于我不希望在示例中调用实际的服务器,因此我抛出putCallToServer()。这将返回2的结果。
我也将结果更改为let变量,因为您正试图对不允许的const进行突变。
async function putCallToServer() {
throw "too lazy to make a real error"
}
// func1
const func1 = async() => {
try {
await putCallToServer();
return 1; // it returns as a promise
} catch(ex) {
return 2;
}
}
// func2
const func2 = async() => {
let result = 0;
result = await func1(); // should I turn it into await func1()??
console.log(result); // log contains '0' instead of '1' or '2'
return result; // return as Promise but value inside is 0
}
func2()