Home > Blockchain >  Javascript async/await not working as expected
Javascript async/await not working as expected

Time:10-22

I am using async/ await but it is not working as expected. The data is being updated before the promise is resolved.

export const update = async (req, res) => {
let lead = Lead.findbyid(id)
let updates = req.body.updates
if (updates.clientDetails.alternateContacts && updates.clientDetails.alternateContacts.length > 0) {
      updates.clientDetails.alternateContacts.forEach(async ele => {
        if (ele.addedOn) console.log('date exists')
        else ele.addedOn = new Date()

        if (ele.email) {
          console.log('11111111111111111111');
          let clientId = await createAutoAccount({ email: ele.email, name:ele.name, contactNumber: ele.phoneNumber })
          console.log('22222222222222222222222', clientId);
          ele.userId = clientId
        }
      })
      lead.clientDetails.alternateContacts = updates.clientDetails.alternateContacts
    }

await lead.save();
}
export const createAutoAccount = async (data) => {
let user = await User.findOne({ email: data.email });
    if (user) {
      console.log('user found =======================', user._id);
    } else {
      console.log('new user created ---------------');
      const tempObj = {
        email: data.email,
        password: data.password ? data.password : 'user123',
        full_name: data.name ? data.name : null,
        contact_number: data.contactNumber && !isNaN(data.contactNumber) ? data.contactNumber : null,
      };
      user = await User.create(tempObj);
    }

    return user._id;
}

The order of output is:

11111111111111111111

update lead

user found ======================= 617155c8827ab456041342ad

22222222222222222222222 617155c8827ab456041342ad

what is want is:

11111111111111111111

user found ======================= 617155c8827ab456041342ad

22222222222222222222222 617155c8827ab456041342ad

update lead

Please let me know what needs to be modified to make this work as per expectations.

CodePudding user response:

I couldn't find where does the update lead log came from. But I think it should be coming from the lead.save(). If it is, the problem should be the async callback of the forEach loop.

updates.clientDetails.alternateContacts.forEach(async ele => { ... })

When you using forEach method, it accept a callback. The await in the for each method, which is the following apply only the that callback

if (ele.addedOn) console.log('date exists')
        else ele.addedOn = new Date()

        if (ele.email) {
          console.log('11111111111111111111');
          let clientId = await createAutoAccount({ email: ele.email, name:ele.name, contactNumber: ele.phoneNumber })
          console.log('22222222222222222222222', clientId);
          ele.userId = clientId
        }
      })
      lead.clientDetails.alternateContacts = updates.clientDetails.alternateContacts

Try to make the await execution context to update function instead of the callback of the forEach by changing to the following code.

export const update = async (req, res) => {
let lead = Lead.findbyid(id)
let updates = req.body.updates
if (updates.clientDetails.alternateContacts && updates.clientDetails.alternateContacts.length > 0) {
      // Use normal for loop instead of forEach with callback, the execution context will be the update function
      for(const alternateContracts of updates.clientDetails.alternateContacts) {
        if (ele.addedOn) console.log('date exists')
        else ele.addedOn = new Date()

        if (ele.email) {
          console.log('11111111111111111111');
          let clientId = await createAutoAccount({ email: ele.email, name:ele.name, contactNumber: ele.phoneNumber })
          console.log('22222222222222222222222', clientId);
          ele.userId = clientId
        }
      })
      lead.clientDetails.alternateContacts = updates.clientDetails.alternateContacts
    }

await lead.save();
}

CodePudding user response:

I don't have enough rep to comment, so this should probably be a comment, but look at this post.

Using async/await with a forEach loop

From what I know your issue is due to you trying to use async await within a foreach loop. I have run into issues with that in the past.

  • Related