0

I am trying to push within a loop in an asynchronous function, but the data that is entered into this array is not saved after the loop ends. What would I be doing wrong?


    for (cont = 0; cont < 3; cont += 1) {
      console.log(cont);

      sqs.receiveMessage(paramsReceiveMessage, (err, data) => {
        if (err) {
          console.log('Receive Error', err);
        } else if (data.Messages) {
          const [{ MD5OfBody }] = data.Messages;
          sqsMessages.push(MD5OfBody);

          console.log(sqsMessages);
        }
      });
    }

    const result = await Promise.all(sqsMessages);

    console.log(result);

    return result;

My response:

2019-11-04T14:35:12.219Z    f00e1408-3ec6-4290-914a-eae4efb23939    INFO    0
2019-11-04T14:35:12.221Z    f00e1408-3ec6-4290-914a-eae4efb23939    INFO    1
2019-11-04T14:35:12.223Z    f00e1408-3ec6-4290-914a-eae4efb23939    INFO    2
2019-11-04T14:35:12.224Z    f00e1408-3ec6-4290-914a-eae4efb23939    INFO    []
Morishiri
  • 874
  • 10
  • 23
Sergio RBJ
  • 43
  • 2
  • 8

2 Answers2

1

Your callback function in sqs.receiveMessage() is still active when the code later reaches the await Promise.all(), so your sqlMessages-array is still empty. You need to wait for the promises in that array to be completed.

In other words, create an array with promises and then wait for them. Something like this:

const promises = [];

for (cont = 0; cont < 3; cont += 1) {
    console.log(cont);

    promises.push(new Promise((resolve, reject) => {

        sqs.receiveMessage(paramsReceiveMessage, (err, data) => {
            if (err) {
                console.log('Receive Error', err);
                reject(err);
            } else if (data.Messages) {
                const [{ MD5OfBody }] = data.Messages;
                sqsMessages.push(MD5OfBody);
                console.log(sqsMessages);
                resolve(MD5OfBody);
            }
        });
    }));
}

const result = await Promise.all(promises);

console.log(result);
Martin Wickman
  • 19,662
  • 12
  • 82
  • 106
0

Looking at your code I would expect the second to last statement ( console.log(result); ) to execute before anything else - and that means the consoled result will be empty.

If the rest of the code is correct (which I can't quite tell), you should be able to console.log the result (last line of code shown) in the place where the return comes back.

pseudocode:

containing function(){
    console.log(yourCodeInFunction());
}

That console should give a result, because it won't run till your messages are received.

Katinka Hesselink
  • 3,961
  • 4
  • 20
  • 26