0

From the below code, I'm trying to get the userId for each user in the list and add it to userRec array, using await for the promise to be resolved before going to next step. I expect the logs to be printed in the following order 1,3,4,2.

But the result I'm getting is in the following order 1,3,2,4.

@wire(getDataRecords,{
    dataId : '$dataId'
})
returnedDataRecord({error,data}){
    if(data){
        var userRec = [];
        data.forEach(async (element) => {
            console.log("1. looking for element Id");
            element.userId = await this.getUserId(element.Id);
            userRec.push(element);
        });
        console.log("2. looking for userRec",userRec);
        this.records = userRec;
    }
}

getUserId(id){
    console.log("3. looking for the Id");
    getUserRecid({
        id: id
    })
    .then((data) => {
        console.log("4. successfully retreived ID");
    })
    .catch((error) => {

    })
}

1 Answer 1

2

You need to return a Promise to make await/async work as you expect.

getUserId(id){
  return new Promise((resolve, reject) =>
    console.log("3. looking for the Id");
    getUserRecid({
        id: id
    })
    .then((data) => {
        console.log("4. successfully retreived ID");
        resolve(data);
    })
    .catch((error) => {
        reject(error);
    })
  });
}

Or, you can use async/await here, too:

async getUserId(id){
  console.log("3. looking for the Id");
  const result = await getUserRecid({ id });
  console.log("4. successfully retreived ID");
  return result;
}

Also, this would have pretty horrible performance. You should use Promise.all to resolve as many calls as you can at once:

var userRec = await Promise.all(data.map(async (element) => {
    console.log("1. looking for element Id");
    element.userId = await this.getUserId(element.Id);
    return element;
}));

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .