我应该在异步函数中抛出错误或返回被拒绝的承诺吗? [英] Should I throw an error or return a rejected promise inside an async function?

查看:185
本文介绍了我应该在异步函数中抛出错误或返回被拒绝的承诺吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 AWS JS SDK 提供的承诺。当我创建包装AWS SDK的异步函数时,我正在做的事情的主旨如下:

I'm working with the promises provided by the AWS JS SDK. The gist of what I'm doing when I create an async function that wraps the AWS SDK looks like this:

module.exports.myCustomFunction = input => {

    if (badInput) {
        throw new Error('failed') // <-- This is they key line
    }

    return sns.createTopic(someParams).promise()
}

// The caller looks like this:
myModule.myCustomFunction(someInput).then(result => {
    // carry on
})
.catch(err => {
    // do something with the error
})

有人说我不应该在这些基于承诺的函数中抛出错误。他们建议返回 Promise.reject('failed')。说实话,我不是那么精通承诺,所以他们的解释有点过头了。

I was approached by someone who said that I should never throw an error inside these kinds of promise-based functions. They suggested returning Promise.reject('failed') instead. To be honest I'm not that well versed in promises yet so their explanation kind of went over my head.

推荐答案

他们是正确。

myCustomFunction 的调用假设始终返回承诺( .then .catch 分别处理已解决和拒绝的承诺)。当你抛出一个错误时,该函数不会返回一个promise。

The call to myCustomFunction assumes that a promise is returned at all times (.then and .catch deal with resolved and rejected promises, respectively). When you throw an error, the function doesn't return a promise.

可以使用它来捕获错误:

try {
  myModule.myCustomFunction(someInput).then(result => {
    // carry on
  })
  .catch(err => {
    // do something with the error
  })
} catch(err) {
  ...
}

但正如您所看到的,这导致两个错误处理程序: try / catch 表示同步抛出错误, .catch 表示任何被拒绝的承诺 sns.createTopic( someParams)可能会返回。

But as you can see, this results in two error handlers: try/catch for the synchronously thrown error, and .catch for any rejected promises that sns.createTopic(someParams) may return.

这就是为什么最好使用 Promise.reject()

That's why it's better to use Promise.reject():

module.exports.myCustomFunction = input => {

    if (badInput) {
        return Promise.reject('failed');
    }

    return sns.createTopic(someParams).promise()
}

然后, .catch 将捕获两种类型的错误/拒绝。

Then, the .catch will catch both types of errors/rejections.

注意:对于较新版本的Node.js(我相信v7.6及以上版本),以下内容也适用:

NB: for newer versions of Node.js (v7.6 and up, I believe), the following will also work:

module.exports.myCustomFunction = async input => {

    if (badInput) {
        throw new Error('failed');
    }

    return sns.createTopic(someParams).promise()
}

这里的关键是 async 关键字。通过使用此关键字,函数结果将自动包含一个promise(类似于@peteb的答案所示)。

The key here is the async keyword. By using this keyword, the function results are wrapped by a promise automatically (similar to what @peteb's answer is showing).

这篇关于我应该在异步函数中抛出错误或返回被拒绝的承诺吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆