0

I'm using a loop to query events, but the code after the loop is not executed. Why is this the case and how do I solve this problem?

router.post("/components/Pages/BrokerAPage/queryAll", (req, res) => {
  var requestedResult;

  for (i = 0; i < EventIDList.length; i++) {
      queryEvent(EventIDList[i])
          .then((result) => {
              if (result) {
                  requestedResult += result;
              }
          })
          .catch(err =>
              res.send(JSON.stringify({ status: 'error', message: err.message})));
    }
    console.log("*************TEST************")
    console.log("*************"+requestedResult+"*************")
    res.json(JSON.stringify(requestedResult));
});
8
  • but queryEvent is fired multiple times? Commented Mar 6, 2018 at 11:12
  • It should be executed but requestedResult is empty Commented Mar 6, 2018 at 11:12
  • 1
    This is an async issue. You have to wait until all calls to queryEvent are finished. Otherwise you might get to your last three lines of code before requestedResult holds the expected output. Commented Mar 6, 2018 at 11:14
  • Your for loop is not synchronous. After promise is return, print requestedResult. Commented Mar 6, 2018 at 11:14
  • 1
    Its empty cause promises are resolve async. When requestedResult is outputted the queryEvent promises are not done. You should store queryEvent in array an use Promise.all() Commented Mar 6, 2018 at 11:17

2 Answers 2

1
router.post("/components/Pages/BrokerAPage/queryAll", (req, res) => {
    var requestedResult;
    var promises = [];
    EventIDList.forEach((EventID) => {
        // gather all Promises
        promises.push(queryEvent(EventID)
            .then((result) => {
                if (result) {
                    requestedResult += result;
                }
            }));
    });
    // wait till all promises are settled, then log result 
    Promise.all(promises).then(() => {
        console.log("*************TEST************");
        console.log("*************" + requestedResult + "*************");
        res.json(JSON.stringify(requestedResult));
    }).catch(err => res.send(JSON.stringify({
        status: "error",
        message: err.message
    })));
});
Sign up to request clarification or add additional context in comments.

Comments

0

You can use async npm module to make the loop synchronous.

router.post("/components/Pages/BrokerAPage/queryAll", (req, res) => {
  var requestedResult;
async.eachOf(EventIDList, function(EventId, index, acb) {
queryEvent(EventId)
          .then((result) => {
              if (result) {
                  requestedResult += result;
                  return acb(null);
              }
          })
          .catch(err =>
              res.send(JSON.stringify({ status: 'error', message: err.message})));
           return acb(null);
    }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.