首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用异步的节点bcrypt

使用异步的节点bcrypt
EN

Stack Overflow用户
提问于 2018-11-02 10:43:11
回答 1查看 978关注 0票数 0

我对NodeJs很陌生,我试图用bcrypt库加密一个文本,

为了串行地执行代码,我使用异步系列函数,

我有两个函数来加密文本,我将它们插入到一个数组中,并将数组传递给async.series函数,

但只有第一个方法被执行。

以下是我的代码-

代码语言:javascript
复制
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);
});
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-11-02 11:09:26

在函数执行之后,您将不进行回调,因此只有一个函数是执行的。你应该给我回电话。

代码语言:javascript
复制
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);

        });
    });
});

}

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

代码语言:javascript
复制
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)
    });
})

}

我希望它能对你有用。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53117043

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档