JAVASCRIPT-Async不等待,直到函数完成? [英] Javascript - async await not wait until function is done?
本文介绍了JAVASCRIPT-Async不等待,直到函数完成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
// 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
}
如果我有一个函数3,它将调用函数2,我是否应该将函数3也转换为异步等待?
推荐答案
如注释中所述,这两个函数必须同步才能使用AWait。这可以在下面的代码片段中看到。(因为我不希望在示例中调用实际的服务器,所以我抛出了putCallToServer()。这将返回%2的结果。
我还将Result更改为let变量,因为您试图静音不允许的常量。
数据-lang="js"数据-隐藏="假"数据-控制台="真"数据-巴贝尔="假">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()
这篇关于JAVASCRIPT-Async不等待,直到函数完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文