0

I'm new to React and I'm trying to make an Api call to a server then using this this data in my component.

I'm trying to use async await to handle asynchronous

const onNotifReceived = async (res) => {
    var updatedQueue = res.updatedQueue;
    updatedQueue["queueNewState"] = await getContactDetails(authClient, res.updatedQueue.queueNewState);
    console.log(JSON.parse(JSON.stringify(updatedQueue)))
    notifyQueue(updatedQueue); // redux dispatcher
}

I notice that console.log(JSON.parse(JSON.stringify(updatedQueue))) is run before other console.logsinside the function getContactDetails.

But as I know await should wait for the response before passing to the next line which is not the case and the problem that I'm not getting updatedQueue["queueNewState"] new state.

1 Answer 1

1

Maybe getContactDetails() do not return a promise, but there are delayed operations in.

async function xd() {
    await xdd();
    console.log("after xdd");
}
function xdd() {
    setTimeout(() => {
        console.log("1000 later");
    }, 1000);
}
xd();
// after xdd
// (after 1 second)
// 1000 later
async function xd() {
    await xdd();
    console.log("after xdd");
}
function xdd() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            console.log("1000 later");
            resolve();
        }, 1000);
    });
}
xd();
// (after 1 second)
// 1000 later
// after xdd

For first situation, xdd runs before console.log("after xdd");, but console.log("1000 later"); will comes out 1 second later.

Sign up to request clarification or add additional context in comments.

1 Comment

Also, objects with function then are treated the same as promises.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.