0

I had a code like this :

router.post('/call' , async (req , res)=>{
    try{
        await async.mapLimit(req.body.n , 5 , (id , callback)=> {
            ////do something
            callback("message")
        }, (err , rest)=>{
            if(err){
                res.json({message : err})
            }else{
                res.json({message : rest})
            }
        })

    }catch(err){
        res.json({message : err})
    }
})

and i want to make the "do something part" a function like this:

router.post('/call' , async (req , res)=>{
    try{
        await async.mapLimit(req.body.n , 5 , (id , callback)=> {
            addStudentID(req , res , id , callback)
        }, (err , rest)=>{
            if(err){
                res.json({message : err})
            }else{
                res.json({message : rest})
            }
        })

    }catch(err){
        res.json({message : err})
    }
})

my problem is that it seems that callback can not sent as a parameter to another function is there any solution to do that?

behnam
  • 100
  • 1
  • 8
  • Please add the error you are getting, if any. –  Sep 15 '19 at 06:23
  • 2
    `await` only does something useful when you `await` a promise. So, awaiting a function that takes a callback and does not return a promise will NOT wait for the callback to be called. – jfriend00 Sep 15 '19 at 06:46
  • Make sure that all of your functions use async/await or promises, and use a for loop instead of the async module – Nicolas El Khoury Sep 15 '19 at 07:35

2 Answers2

0

First, async in function declaration is useless unless you await promise function (async-await function). But I don't know why you passing a function as a callback to a promise function (async-await function).

Then, let's assume that your async.mapLimit is callback based function. You can wrap your callback function with promise then produce async-await function (function that return promise) like below:

function async.mapLimitPromise(firstArgument, secondArgument) {
  return new Promise(function(resolve, reject) {
    async.mapLimit(firstArgument, secondArgument, function(err, data) {
    if (err) {
      reject(err)
    }
    resolve(data)
  })
})

But one more thing. I don't understand why you pass a function (your callback) as a 3rd argument of a async.mapLimit function, but then it receive a callback as second argument

I recommend you to read more about callback function first, then a promise, and last you can try async function

---Edit---

Try with this code first:

router.post('/call' , async (req , res)=>{
  try{
    const res = await async.mapLimit(req.body.n , 5 , (id , callback)=> {
      addStudentID(req , res , id , callback)
    })
    res.json({message : rest})

  }catch(err){
    res.json({message : err})
  }
})
nnfans
  • 131
  • 1
  • 9
0

problem was problem with function usage and function declaration that were not sync not the callback part

behnam
  • 100
  • 1
  • 8