Question

guys, really need for your helps. I got some code block as follows:

function readyToSubmit(answerPack, answerArr, len) {
  for (var i = 0; i < answerArr.length; i++) {
    var questionId = answerArr[i].id;
    console.log(questionId);

    // below is an database async operation
    userStore.getDoc(id).then(function(doc) {
      // if I console.log 'answerArr[i]' here, it will be undefined
      // I know it's 'cause the 'i' here is answerArr.length, so it would be undefined
      // I want my questionId differently, but it is always the last one in the array
      // I know it's the closure issue, but don't really know how to handle it.

      doc.questionId = questionId; // always the same one
      answerPack.push(doc);
    });
  }
}

So, how can I exactly get what I want in every round, I mean different questionId, not always the last one. Many many thanks, :)

Was it helpful?

Solution

You could so somethink like ,

function readyToSubmit(answerPack, answerArr, len) {
    for (var i = 0; i < answerArr.length; i++) {
        var questionId = answerArr[i].id;
        doasynch(questionId);
    }
}

function doasynch(questionId) {
    userStore.getDoc(id).then(function (doc) {
        doc.questionId = questionId;
        answerPack.push(doc);
    });
}

Read

  1. How Closure works
  2. Closure inside loop issue
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top