使用异步的节点bcrypt

时间:2018-11-02 10:43:11

标签: node.js bcrypt async.js

我是NodeJ的新手,我正在尝试使用bcrypt库对文本进行加密,
要串行执行代码,我正在使用异步序列函数,
我有两个用于加密文本的函数,我将它们插入Array并将该数组传递给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);
});

1 个答案:

答案 0 :(得分: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)
    });
})

}

我希望它对您有用。