raju
raju

Reputation: 6936

Using callback function inside array.map javascript

I am trying to bcrypt password for every user in an array.

router.post("/insertuser", (req, res) => {

  var promises = users.map((item) => {

    bcrypt.genSalt(10)
      .then((salt) => {
        return item
      })    
  })

  Promise.all(promises)
    .then((results) => {
      console.log(results)
      res.json({
        "data": results
      })
    })    
})//end route

But I am getting results = [undefined,undefined].

How can I return array element from bcrypt.genSalt(10).then

Please help as I am new to ES6

EDIT: My user users array is like this:

[{ "username": "admin", "admin": true} ]

Upvotes: 0

Views: 1349

Answers (2)

Amit Singh
Amit Singh

Reputation: 436

When you add .then() after any promise it will directly get resolved. In your code users.map() will run synchronously and the promises will have undefined. Here is the code you can use :

router.post("/insertuser", (req, res) => {
    var promises = users.map((item) => {
      return bcrypt.genSalt(10);
    })

    Promise.all(promises)
      .then((results) => {
        console.log(results)
    });  
})//

Also notice that salt is used to generate hash. You are only generating salt. To generate hash of password also add bcrypt.hash(password,salt). Here is the code :

var promises = users.map((item) => {
  return bcrypt.genSalt(10);
})

Promise.all(promises)
  .then((results) => {
    promises = results.map((item, index) => {
      return bcrypt.hash(users[index], item);
    });
    return Promise.all(promises);
  })
  .then(result => {
    console.log(result);
  })
  .catch(err => {
    console.log(err);
  });

Upvotes: 0

Shailendra Pal
Shailendra Pal

Reputation: 123

Simply return the promise from bcrypt.genSalt.

router.post("/insertuser", (req, res) => {

  var promises = users.map((item) => {

    return bcrypt.genSalt(10)
      .then((salt) => {
        return item
      })    
  })

  Promise.all(promises)
    .then((results) => {
      console.log(results)
      res.json({
        "data": results
      })
    })    
})//end route

Upvotes: 1

Related Questions