Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write callback function inside for loop in node.js

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.

like image 937
Sukhesh Chukkapalli Avatar asked Jul 28 '26 03:07

Sukhesh Chukkapalli


2 Answers

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
});
like image 55
Michael Hirschler Avatar answered Jul 30 '26 18:07

Michael Hirschler


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';
}
like image 26
PeterMader Avatar answered Jul 30 '26 18:07

PeterMader