sai
sai

Reputation: 527

How to use .then or await inside a for loop in nodejs?

I have a Nodejs function which registers for an event to get the data and do some manipulations and then insert in to an Elastic DB. My code looks like below.

async function callB() {
    var block_reg = channel_event_hub.registerBlockEvent((block) => {
        const transactionArray = block.data.data;

        for (const trans of transactionArray) {
            var writeSet = trans.payload.data.actions[0]

            for (const writes of writeSet) {
                var updatefunc = validateVlaues(writeSet);

                updatefunc.then(function (result) {
                    EP.push(numberjson);
                    EP.push(result);
                })
            }
        }

        console.log("EP ", EP.length); // Executing even before .then

        elasticClient.bulk({
            index: 'indexdata',
            type: '_doc',
            body: EP,
        }
      }, (error) => {
    });
}

Please help me with this. Or how can I use await in this scenario. Function is an async function, but inside Blockevent how can i use await . Im stuck with this for long time. Can anybody suggest me how to preoceed?

Upvotes: 0

Views: 64

Answers (2)

Keimeno
Keimeno

Reputation: 2644

You're inside a callback. You must make the callback async.

async function callB() {
                                                   // here
 var block_reg = channel_event_hub.registerBlockEvent(async (block) => {
     const transactionArray = block.data.data;
     ...

Then you can await the Promise:

const result = await updatefunc;

Upvotes: 3

Terry Lennox
Terry Lennox

Reputation: 30685

You can use a for, for..of, while, etc loop type along with await as long as the function is an async function.

For example, if you're calling a function that reads data from an api that returns a Promise, you can await the result within the loop and everything will work as you expect.

The await syntax is also more readable then the .then syntax IMHO.

// function reading user details from https://jsonplaceholder.typicode.com/users
async function getDataFromApi(userId) {
    return await fetch(`https://jsonplaceholder.typicode.com/users/${userId}`)
        .then(response => response.json());
}


// Read results from all ids
async function getAllDataFromApi() {
    let ids = [1,2,3];
    for(let id of ids) {
        console.log(`Getting data from api for user id ${id}...`);
        let result = await getDataFromApi(id);
        console.log(`Result from api for user id ${id}:`, result);
    }

}

getAllDataFromApi();

Upvotes: 0

Related Questions