Using callback function inside array.map javascript

后端 未结 2 1305
忘掉有多难
忘掉有多难 2021-01-25 23:44

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

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

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

    bcrypt         


        
2条回答
  •  失恋的感觉
    2021-01-26 00:23

    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);
      });
    

提交回复
热议问题