0

I have a loop that calls executepostaction with an object. The problem is that executepostaction only execute the last value of the loop. I've tried many closures and here I am trying to fix using setTimeout but still no luck. What seems to be the problem?

my timeout function:

function MakeTimeout(fn, data, timeout) {
            setTimeout(function () { fn.call(null, data); }, timeout);
        }

This is the loop from an event function:

for (var ctr = 0; ctr < Selectrows.length; ctr++) {
                    
                    var action=  selectedAction;
                    action["trackId"] = Selectrows[ctr].innerText.replace(/(^\d+)(.+$)/i, '$1');
                    
                    MakeTimeout(function (passaction) {

                        researchService.postExecuteAction(passaction)
                                   .then(function (result) {
                                   }, function error(result) {
                                       $scope.error = result;
                                   });
                    }, action, ctr * 1000);
                }

Please help. Thank you

2 Answers 2

1

I see a few problems there, not sure exactly what you are trying to do but seems that you want to call a promise for each value of an array.

Guessing you are able to use ES6 and that each call are async, I would do something like this:

Selectrows.forEach(row => {
  const action = {
    ...selectedAction,
    trackId: row.innerText.replace(/(^\d+)(.+$)/i, '$1')
  };
  
  researchService.postExecuteAction(action)
   .then(function (result) {
      // Do something
   }, function error(result) {
       $scope.error = result;
   });
});

  1. First is using forEach instead of for if Selectrows is an array.
  2. Clone the object selectedAction bc if you just assign it you are using the same object each time, bc objects and arrays are reference types.
  3. Seems that you don't need a timeout, or do you? each promise will be executed in parallel and will response as soon as the promise return a response.
Sign up to request clarification or add additional context in comments.

Comments

0

You can use spread syntax to create a copy of the object before modifying it.

var action = {...selectedAction};

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.