简体   繁体   中英

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. 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. And, you don't need to declare the promise executor callback as async either. And, if you're using await inside the executor, then you don't need to wrap it with a manually created 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. 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 . 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() :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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