How to make async in NodeJs

时间:2019-04-17 00:54:36

标签: javascript node.js asynchronous async-await

In my async function, I can't get true priority output.

Expected result is firstly {control : 1} and then {control : 2}.

But the result is vice versa.

How can I make it true ?

NodeJS Code

edit_settings = async function (params) {

    await User.updateOne({ _id: params.id }, query, (error, update_result) => {
        console.log({ control : 1 });
        if (error) return { success: false, error: { code: 1001 } };
        else return { success: update_result.nModified };
    });

    return await { control : 2 };
}

NodeJS Result

{ control : 2 }
{ control : 1 }

2 个答案:

答案 0 :(得分:2)

It doesn't look like User.updateOne returns a promise (could be wrong, but I'm guessing it doesn't), it accepts a callback, so await-ing it will do nothing.

EDIT: One way to solve it is to create a promise like this:

edit_settings = async function (params) {
    let res; // the `resolve` method of a promise
    const p = new Promise(r => res = r);
    User.updateOne({ _id: params.id }, query, (error, update_result) => {
        console.log({ control : 1 });
        res(); // resolve the promise
        if (error) return { success: false, error: { code: 1001 } };
        else return { success: update_result.nModified };
    });

    await p;
    return { control: 2 };
}

EDIT: Based on your comment that User.updateOne actually does return a promise, then you should be using it like this:

edit_settings = async function (params) {

    await User.updateOne({ _id: params.id }, query);
    console.log({control:1});
    return { control : 2 };
}

From the code you've shown, you actually aren't doing anything with the value you're returning from the promise, so I removed it from your code.

答案 1 :(得分:0)

I found the solition:

edit_settings = async function (params) {

    let result;

    ..

    result = await User.updateOne({ _id: params.id }, query).then(update_result => {
        result = { success: update_result.nModified };
    });

    ..

    return await result ;
}