假设我有这样的代码:
function doSomething() {
const foo = await new Promise((resolve, reject) => {
//...
reject();
}).catch(error => {
//I'd like to exit the doSomething function since the promise rejected
return;//This only exists the this arrow funtion
});
console.log('Should not get to here if foo rejects');
}
如果foo
返回一个被拒绝的promise,那么我想退出doSomething()
,但上面的代码并不能做到这一点。相反,由于error
被捕获,代码将继续。
如果我没有catch
拒绝的承诺,那么我会得到一个错误:UnhandledPromiseRejectionWarning
:
function doSomething() {
const foo = await new Promise((resolve, reject) => {
//...
reject();
});
console.log('Should not get to here if foo rejects');
}
我知道我可以做到,但这感觉很混乱:
function doSomething() {
let exitFunction = false;
const foo = await new Promise((resolve, reject) => {
//...
reject();
}).catch(error => {
//I'd like to exit the doSomething function since the promise rejected
exitFunction = true;
});
if (exitFunction) {
return;
}
console.log('Should not get to here if foo rejects');
}
那么,处理这样的事情最好的方法是什么呢?如果能做到这一点就太好了:
function doSomething() {
const foo = await new Promise((resolve, reject) => {
//...
reject();
});
if (foo.rejected) {
return;
}
console.log('Should not get to here if foo rejects');
}
甚至这个:
function doSomething() {
const foo = await new Promise((resolve, reject) => {
//...
reject();
}).catch(error => {
return function2;//Sort of like JS's `break loop2;`
});
console.log('Should not get to here if foo rejects');
}
有人感觉到我的痛苦吗?如果有,最好(最干净)的方法是什么?
如果您在async function
中处理承诺,我建议使用try/catch
function promiseFunc() {
return new Promise((resolve, reject) => {
//...
reject("error!");
});
}
async function doSomething() {
try {
const foo = await promiseFunc();
} catch (err) {
console.log(err);
return;
}
console.log("Should not get to here if foo rejects");
}
doSomething();
我认为您只是误解了return
在第一个代码中返回到
的位置return
返回到foo
这就是它继续的原因
您可以使用foo来捕获像这样的返回结果
async function doSomething() {
let foo = await new Promise((resolve, reject) => {
reject();
}).catch(error => {
return false;
});
if(!foo) return console.log("rejected and stopped");
console.log('Should not get to here if foo rejects');
}
doSomething()
或者像这个
async function doSomething() {
if (!
await new Promise((resolve, reject) => {
reject();
}).catch(error => {
return false;
})
) return console.log("rejected and stopped");;
console.log('Should not get to here if foo rejects');
}
doSomething()