【问题标题】:Node bcrypt using async使用异步的节点 bcrypt
【发布时间】:2018-11-02 19:09:26
【问题描述】:

我是 NodeJs 的新手,我正在尝试使用 bcrypt 库加密文本,
要串行执行代码,我使用的是异步系列函数,
我有两个函数来加密文本,我将它们插入到数组中并将数组传递给 async.series 函数,
但只有第一个方法正在执行。

以下是我的代码 -

const bcrypt = require('bcrypt');
var async = require('async');

const saltRounds = 10;
const myPlaintextPassword = 's0/\/\P4$$w0rD';

var hash1, hash2;
var seriesArray = [];

var one = function(callback){
    bcrypt.genSalt(saltRounds, function(err, salt) {
        bcrypt.hash(myPlaintextPassword, salt, function(err, hash) {
            console.log("Hash 1 => " + hash + "\n");
            hash1 = hash;

            bcrypt.compare(myPlaintextPassword, hash1, function(err, res) {
                console.log("Original Test of Hash1 => " + res + "\n");
            });
        });
    });
}

var two = function(callback){
    bcrypt.hash(myPlaintextPassword, saltRounds, function(err, hash) {
        console.log("Hash 2 => " + hash + "\n");
        hash2 = hash;

        bcrypt.compare(myPlaintextPassword, hash2, function(err, res) {
            console.log("Original Test of Hash2 => " + res + "\n");
        });
    })
}
seriesArray.push(one);
seriesArray.push(two);

async.series(seriesArray,
function(err, results) {
    console.log(results);
});

【问题讨论】:

    标签: node.js bcrypt async.js


    【解决方案1】:

    函数执行后你没有给回调,所以只有一个函数正在执行。你应该给回调。

    var one = function(callback){
    bcrypt.genSalt(saltRounds, function(err, salt) {
        bcrypt.hash(myPlaintextPassword, salt, function(err, hash) {
            console.log("Hash 1 => " + hash + "\n");
            hash1 = hash;
    
            bcrypt.compare(myPlaintextPassword, hash1, function(err, res) {
                console.log("Original Test of Hash1 => " + res + "\n");
                callback(err,res);
    
            });
        });
    });
    

    }

    对于第二个函数,代码应该是

    var two = function(callback){
    bcrypt.hash(myPlaintextPassword, saltRounds, function(err, hash) {
        console.log("Hash 2 => " + hash + "\n");
        hash2 = hash;
    
        bcrypt.compare(myPlaintextPassword, hash2, function(err, res) {
            console.log("Original Test of Hash2 => " + res + "\n");
        callback(err,res)
        });
    })
    

    }

    我希望它对你有用。

    【讨论】:

      猜你喜欢
      • 2023-03-22
      • 1970-01-01
      • 2020-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-05
      • 2018-06-09
      • 1970-01-01
      相关资源
      最近更新 更多