Home > Back-end >  callback is not a function inside async library
callback is not a function inside async library

Time:09-17

I created this small code to reproduce the error I was getting inside an app:

const async = require("async");

function sleep(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

const parallels = [];

for (let i = 0; i < 2; i  ) {
  parallels.push(async function (callback) {
    const randomSleepTime = Math.ceil(Math.random() * 10000);
    await sleep(randomSleepTime);
    callback(randomSleepTime);
  });
}

async.parallel(parallels, function (err, results) {
  console.log(err);
  console.log(results);
});

I'm getting this error after this is done: TypeError: callback is not a function
Why exactly is this happening?

CodePudding user response:

You can remove async/await and use .then instead:

const async = require('async');

function sleep(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

const parallels = [];

for (let i = 0; i < 2; i  ) {
  parallels.push(function (callback) {
    const randomSleepTime = Math.ceil(Math.random() * 100);
    sleep(randomSleepTime).then(() => {
      callback(randomSleepTime);
    });
  });
}

async.parallel(parallels, function (err, results) {
  console.log(err);
  console.log(results);
});

CodePudding user response:

The solution is to return the value instead of using callback() which is mentioned here.

  • Related