gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 17:44:41 24 4
gpt4 key购买 nike

所以我有一个函数应该立即返回一个被拒绝或已解决的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com