简体   繁体   English

如何在异步循环中使用 array.push?

[英]How do i use array.push on async loop?

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.我正在尝试在异步 function 中的循环内推送,但循环结束后不会保存输入到该数组中的数据。 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    []

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.当代码稍后到达await Promise.all()时,您在sqs.receiveMessage()中的回调 function 仍然处于活动状态,因此您的sqlMessages仍然为空。 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.换句话说,创建一个带有 Promise 的数组,然后等待它们。 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);

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.查看您的代码,我希望倒数第二个语句( console.log(result); )在执行其他任何操作之前执行 - 这意味着控制台结果将为空。

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.如果代码的 rest 是正确的(我不太清楚),您应该能够在返回返回的地方控制台记录结果(显示的最后一行代码)。

pseudocode:伪代码:

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

That console should give a result, because it won't run till your messages are received.该控制台应该给出结果,因为在收到您的消息之前它不会运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM