2

I am trying to write a function inside a for loop. But the loop is not waiting until getting response for the function inside. How can I stop the loop until getting response for the function every time?

In this process the next loop is dependent on the response of the function.

My example code:

var a = function(data, callback) {
    var d = 1;
    for (var i = 0; i < data.length; i++) {
        b(d, function(err, result) {
            if (!err) {
                d = result;
            }
            if ((i + 1) === data.length) {
                callback(err, 'something');
            }
        });
    }
}
var b = function(data, callback) {
    var c = data + 1;
    callback(null, c);
}

In this code the for loop is not waiting until it gets the response form the function b.

2
  • 1
    "How can I stop for loop until getting response for the function on every time." You cannot. for is synchronous. Do not use a loop in this case. Commented Sep 1, 2017 at 6:42
  • Thank you for response.But i need this type of operation, How can I ? Commented Sep 1, 2017 at 6:48

2 Answers 2

9

You can easily iterate your input array by calling a recursive function call within your callbacks:

'use strict';

const a = function(data, callback) {
  let i = 0;
  let sum = 0;

  // loop function
  function next() {
    const x = data[i++];
    if (!x) {
      return callback(null, sum);
    }

    return b(x, (err, data) => {
      sum += data;
      next();
    });
  }

  next(); // starts iterating
}

// multiplies data * 3
const b = function(data, callback) {
   let c = data * 3;
   callback(null, c);
}


a([1, 2, 3], (err, data) => {
  console.log(data); // prints 18
});
Sign up to request clarification or add additional context in comments.

Comments

5

Use Promises

Your code can easily be refactored to use Promises:

function a (data) {
  let promise = Promise.resolve(1);
  for (let i = 0; i < data.length; i++) {
    promise = promise.then(b);
  }
  return promise.then(function (v) {
    // v is the value computed by the promise chain
    return 'something';
  });
}

function b (data) {
  // some async action that returns a promise
  return Promise.resolve(data + 1);
}

Usage:

a(['a', 'b', 'c']).then(result => console.log(result)); // logs 'something'

Use async functions

Working with promises allows you to treat asynchronous code like synchronous code using async functions:

async function a (data) {
  let v = 1;
  for (let i = 0; i < data.length; i++) {
    // looks like synchronous code, but is asynchronous
    v = await b(v);
  }
  // v is the value computed by the asynchronous loop
  return 'something';
}

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.