javascript - 我可以只使用异步 "promisify"函数吗?

标签 javascript asynchronous promise ecmascript-2017

所以我有一个函数应该立即返回一个被拒绝或已解决的 Promise,即它基本上是一个我想“promisify”的同步函数。

在这种情况下我通常做的是这样的:

func() {
     // some code to check for an error
     if (hasError)
        return Promise.reject(new Error("Failure"));
     }
     return Promise.resolve("Success");
}

现在,随着 ES2017 中“异步”功能的可用性,我似乎也可以这样做:

async func() {
     // some code to check for an error
     if (hasError)
        throw new Error("Failure");
     }
     return "Success";
}

所以我基本上使用 async 只是为了“promisify”我的函数,而不是在函数体中的任何地方使用 await 。正如我所见,这个变体应该做的完全一样。我是对的,还是有其他我不知道的副作用?

我想我更喜欢这种模式,因为它更短一些,仅从函数定义中就可以清楚地看出它是异步的,并且任何 JavaScript 错误(如类型错误)也会导致拒绝,这使得我整体代码在出现意外错误时 react 更优雅。

最佳答案

每当你声明一个async函数时,一个AsyncFunction对象就会被创建,根据MDN,它会返回一个Promise:

A Promise which will be resolved with the value returned by the async function, or rejected with an uncaught exception thrown from within the async function.

是的,使用 asyncpromisify 一个函数。

另外,让我们做一些测试;

async function fn(val) {
  console.log(val);
  if (val) {
    return "true";
  }
  throw new Error("false");
}

console.log(Object.getPrototypeOf(fn).constructor)

console.log(fn(true) instanceof Promise);
console.log(Object.getPrototypeOf(fn(true)).constructor)

console.log(fn(false) instanceof Promise);
console.log(Object.getPrototypeOf(fn(false)).constructor)

fn(true).then(val => console.log(val));

fn(false).catch(err => console.log("ERROR"));

关于javascript - 我可以只使用异步 "promisify"函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50660103/

相关文章:

python - BigQuery 异步查询作业 - fetch_results() 方法返回错误数量的值

javascript - 如何在 forEach 中一一运行 Promise

firebase - Firestore 离线 promise 处理?

javascript - 如何将 arraybuffer 响应类型转换为 python 中的字符串?

javascript - 如何在 Haml 中使用 JavaScript 变量?

javascript - 获取 websockets 使用关闭代码 1006 关闭的原因

javascript - EcmaScript 语法

javascript - 将自定义消息添加到 knockout 所需的验证

angularjs - 使用异步数据初始化 AngularJS 配置 block

c# - 在 .Net 4.5 中使用 async/await 编写多线程方法