尽管前面提到的异步函数的承诺已经成功实现,但我很难理解为什么这个.catch
方法会被执行。
我希望我的web应用程序在从服务器检索数据失败的情况下向用户显示错误消息。
这是代码:
async function main() {
await asyncSendDataToServer()
.then(result = await asyncReceiveDataFromServer())
.catch(toggle('error'));}
如果不是绝对必要的话,我强烈建议不要混合使用async/await和Promise/then。这只是令人困惑(正如你可能注意到的(。
async function main() {
try {
await asyncSendDataToServer();
const result = await asyncReceiveDataFromServer();
console.log(result);
} catch(e) {
toggle('error')
}
}
如果你真的想用你的风格写它,这里有正确的解决方案:
async function main() {
await asyncSendDataToServer()
.then(() => {
result = await asyncReceiveDataFromServer()
})
.catch((err) => toggle('error'));
}
.then()
中的=>
中缺少>
,catch
中缺少所有() =>
。由于您使用的是then/catch,因此该函数不必是异步的。
function main() {
return asyncSendDataToServer()
.then(result => await asyncReceiveDataFromServer())
.catch(() => toggle('error'));
}
异步公式是
async function main() {
try {
await asyncSendDataToServer();
return await asyncReceiveDataFromServer();
} catch(err) {
toggle('error');
}
}
因为您正在立即执行函数,所以应该传入一个处理错误的匿名函数:
.catch((error) => toggle('error'))
此外,then
语句是错误的,因为它不是一个函数。这是异步/等待的正确方式:
async function main() {
try {
await asyncSendDataToServer();
const result = await asyncReceiveDataFromServer();
} catch(error) {
toggle('error')
}
}
且无异步:
function main() {
return asyncSendDataToServer()
.then(() => asyncReceiveDataFromServer())
.then((result) => console.log(result))
.catch((error) => toggle('error'));
}