用JavaScript实现带有Promise的快速失败设计

我不确定“快速失败”是否是描述这种方法的最佳方法,但是自从我开始学习编程以来,我总是被教导设计这样的函数:

function doSomething() {
    ... // do error-prone work here

    if (!allGood) {
        // Report error,cleanup and return immediately. Makes for cleaner,// clearer code where error-handling is easily seen at the top
        ...
        return;
    }

    // Success! Continue on with (potentially long and ugly) code that may distract from the error
}

正因为如此,我试图像这样调用一个承诺函数:

doSomethingAsync(param).catch(err => {
    console.error(err);
}).then(() => {
    // Continue on with the rest of the code
});

但是,这使我的行为类似于经典finally语句的try...catch...finally块,即then()块将被始终调用,即使在错误。有时候这很有用,但是我很少发现自己需要这种功能(或者一般来说,try...catch语句)。

因此,为了尽可能快速,清晰地排除故障,有没有一种方法可以使我上面的第二个示例按我期望的方式工作(即,then()仅在{{1} }不是,但是一个catch()仍会捕获catch()引发的所有错误吗?

qinjilei 回答:用JavaScript实现带有Promise的快速失败设计

如果您使用asyncawait而不是.then,则可以有效地等待Promise解决(或拒绝),如果拒绝,则提早返回:

(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仅{em> 处理doSomethingAsync(param)引发的错误。如果您的onResolve也可以扔进它的主体中,那么您就必须在其上链接另一个.catch(这看起来会有些混乱-通常更好地在一个地方捕获错误) )

本文链接:https://www.f2er.com/2800605.html

大家都在问