Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using 'await' and 'async' correctly in NodeJS

I have this piece of code:

function func(x) {
    return func2(x)
        .then((result) => {
            let a = await func3(result.a);
            let b = await func3(result.b);
            return {'a': a, 'b': b};
        });
}

And I need to put async() somewhere, but I am unable to figure out where.

I tried before the => and after the =>, but I got a syntax error in both cases.

P.S, if I use it in the declaration of func, then I get a runtime error await is a reserved word.

like image 823
goodvibration Avatar asked Feb 11 '26 06:02

goodvibration


1 Answers

I think you want to achieve something like that

function func(x) {
    return func2(x)
        .then(async (result) => {
            let a = await func3(result.a);
            let b = await func3(result.b);
            return {'a': a, 'b': b};
        });
}

or

async function func(x) {
    const result = await func2(x)
    let a = await func3(result.a);
    let b = await func3(result.b);
    return {'a': a, 'b': b};
}

Considering your edited question, it seems that you are using a version of nodejs that does not support async/await

like image 56
ThomasThiebaud Avatar answered Feb 15 '26 19:02

ThomasThiebaud



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!