使用异步的节点 bcrypt

Node bcrypt using async

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

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

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

}

希望对你有用。