Javascript承诺:抓住流量

时间:2017-01-18 10:07:54

标签: javascript ecmascript-6 promise es6-promise

在以下代码中,我希望能够在 foo 失败时退出应用,但不能在 goo 失败时退出应用。我的问题是当 goo 拒绝时,它会被 foo 捕获。对这个问题有承诺最佳实践解决方案吗?

foo().then(() => {
    return goo.catch(() => {
        //do something
        //reject but don't exit app
    })
})
.catch(() => {
    //exit app
    //reject
})

4 个答案:

答案 0 :(得分:3)

请勿在{{1​​}}中拒绝 - 您不希望拒绝传播到goo.catch处理程序。

foo.catch

所以你输入catch block并从错误情况中“恢复”。通过抛弃/拒绝你进一步传递异常,如果foo().then(() => { return goo.catch(() => { // do something but don't reject }) }) .catch(() => { // exit app // reject }) 你不想要这个。

答案 1 :(得分:1)

来自return阻止{或goo.catch()}

Promise.resolve()
const gooError;

foo().then(() => {
    return goo.catch(err => {
        // set the error thrown in to gooError that is
        // declared before the promise chain
        // and then simply 'return'
        gooError = err;
        return;
    });

    // to ensure goo error is taken outside immediately
    // You can omit this if not required.
    if (gooError) return; 

})
.catch(() => {
    // exit app
    // reject
})

// check if there was any error by goo
if (gooError) {
    // handle goo error here
}

答案 2 :(得分:1)

我认为这就是诀窍:

foo()
.catch(() => {
    //exit app
    //reject
})
.then(() => {
    return goo.catch(() => {
        //do something
        //reject
    })
})

答案 3 :(得分:1)

让我们看一下你想在同步代码中实现的目标:

function main() {
    try {
        foo();
    } catch(e) {
        console.log("Exit process");
        throw e;
    }
    try {
        goo();
    } catch(e) {
        console.log("do something");
        throw e;
    }
}

您可以通过嵌套捕获来实现此目的:



function foo() {
  return Promise.reject();
}

function goo() {
  return Promise.reject();
}

function main() {
  return foo().catch(e => {
    console.log("Exit process");
    // what would be point in rejecting if the process already exited anyway?
    throw e;
  }).then(() => {
    return goo().catch(e => {
      console.log("Do something");
      throw e;
    });
  });
}

main().catch(() => { console.log("Main is rejected"); });