goodvibration
goodvibration

Reputation: 6206

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.

Upvotes: 3

Views: 92

Answers (2)

ThomasThiebaud
ThomasThiebaud

Reputation: 11969

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

Upvotes: 3

goodvibration
goodvibration

Reputation: 6206

Got it:

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

Upvotes: 0

Related Questions