如果你使用
async
和
await
而不是
.then
,您可以有效地等待承诺解决(或拒绝),如果它拒绝,请提前返回:
(async () => {
try {
await doSomethingAsync(param);
} catch(err) {
console.error(err);
return;
}
// Continue on with the rest of the code
})();
const doSomethingAsync = () => new Promise((resolve, reject) => Math.random() < 0.5 ? resolve() : reject('bad'));
(async () => {
try {
await doSomethingAsync();
} catch(err) {
console.error(err);
return;
}
console.log('continuing');
})();
.then(onResolve, onReject)
技术,虽然是
usually not recommended
:
function onReject(err) {
console.log(err);
};
doSomethingAsync(param).then(onResolve, onReject);
function onResolve() {
// Continue on with the rest of the code
}
const doSomethingAsync = () => new Promise((resolve, reject) => Math.random() < 0.5 ? resolve() : reject('bad'));
function onReject(err) {
console.log(err);
};
doSomethingAsync().then(onResolve, onReject);
function onResolve() {
console.log('continuing');
}
这将有
onReject
只有
处理由引发的错误
doSomethingAsync(param)
onResolve
也可以扔进它的身体里,那你就得把另一个链子拴起来
.catch
在它上面(这将开始看起来有点混乱-只在一个地方发现错误通常更好)