简体   繁体   English

JS/TS - 在异步函数中返回已解决/拒绝的承诺值

[英]JS/TS - Returning promise resolved/rejected values inside async functions

I am using a function definition in my code which is an async function and it returns values from a Promise with try/catch.我在我的代码中使用了一个函数定义,它是一个异步函数,它从带有 try/catch 的 Promise 返回值。 Something like this :-像这样的东西:-

 async someFunction(parameters) { return new Promise(async(resolve, reject) => { try { // do something like an api call with await and resolve the response resolve(parameters); } catch (error) { reject(error); } }); } someFunction("HEllo world");

I wanted to ask, is this overkill?我想问一下,这是不是有点矫枉过正? am i writing redundant code?我在写多余的代码吗? is this an anti-pattern?这是一种反模式吗?

I wanted to ask, is this overkill?我想问一下,这是不是有点矫枉过正? am i writing redundant code?我在写多余的代码吗? is this an anti-pattern?这是一种反模式吗?

Yes, it's overkill and it's at least two, maybe three anti-patterns.是的,这是矫枉过正,至少有两个,也许三个反模式。

You don't need to declare a function async that you're just returning a manually created promise from.您不需要声明一个函数async ,您只是从中返回一个手动创建的承诺。 And, you don't need to declare the promise executor callback as async either.而且,您也不需要将承诺执行程序回调声明为async And, if you're using await inside the executor, then you don't need to wrap it with a manually created promise.而且,如果您在 executor 中使用await ,那么您不需要用手动创建的 promise 来包装它。

If you're really planning on using await inside the promise executor, then you must already have functions that return promises that you want to use await with.如果您真的打算在 promise 执行器中使用await ,那么您必须已经拥有返回要与await一起使用的 promise 的函数。 If that's the case, then there's no reason to wrap those in a manually created promise.如果是这种情况,则没有理由将它们包装在手动创建的承诺中。 That is a promise anti-pattern.这是一种承诺反模式。

You also don't need to try/catch and then just reject with the same error.您也不需要尝试/捕获然后以相同的错误拒绝。 You can just let the error propagate on its own.您可以让错误自行传播。

So, let's suppose you have two promise-returning functions that you want to run serially using await .因此,让我们假设您有两个要使用await串行运行的 promise 返回函数。 Then, all you need is this:然后,您只需要这样:

async function someFunction(parameters) {

    let v1 = await func1(...);
    // do something with v1
    let v2 = await func2(someValFromV1);
    // do something with v2
    return someValFromV2;
}

someFunction("HEllo world").then(result => {
    console.log(result);
}).catch(err => {
    console.log(err);
});

Or you can call it with await instead of .then() :或者你可以用await而不是.then()来调用它:

async function anotherFunction() {
    let result = await someFunction(...);
    // do something with result
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM