NodeJS:在异步功能之外获取价值

时间:2019-01-22 10:18:56

标签: node.js asynchronous async-await

const _sodium = require('libsodium-wrappers');
(async (model = this._modelUser) => { //Had to pass this._modelUser otherwise it'd be undefined
    await _sodium.ready;
    const sodium = _sodium;

    let password = sodium.crypto_pwhash_str(Utils.urldecode(data.password), 7, 677445);
    model.password = password;
    console.log('In:' + model.password); //Good value
})();

console.log('Out:' + this._modelUser.password); //Undefined

因此,在这种情况下,this._modelUser.password是未定义的外部函数。我想等待this._modelUser获得正确的密码值,然后再继续。

有人知道如何解决此问题吗?谢谢您的帮助

由于语法(async =>())和特定模块的使用而与How do I return the response from an asynchronous call?不同:https://www.npmjs.com/package/libsodium

2 个答案:

答案 0 :(得分:0)

因此async/await的目的是不阻塞,并返回一个Promise对象,您可以使用该对象对返回的内容进行操作。

分配密码后,很难确切知道您打算如何处理模型,但是我建议您使用以下类似的方法将密码分配给当前功能之外的模型:

const _sodium = require('libsodium-wrappers');

const generatePassword = async () => {
    await _sodium.ready;
    const sodium = _sodium;

    // Not sure where you have got data from, could be passed in locally.
    return sodium.crypto_pwhash_str(Utils.urldecode(data.password), 7, 677445);
}

generatePassword()
    .then((password) => {
        this._modelUser.password = password;
    })
    .catch((error) => console.log('error: ', error))

您当然可以将其拆分成更多功能。

答案 1 :(得分:0)

承诺有助于实现这一目标。



const _sodium = require('libsodium-wrappers');
(async (model = this._modelUser) => { d
    await _sodium.ready;
    const sodium = _sodium;

    let password = sodium.crypto_pwhash_str(Utils.urldecode(data.password), 7, 677445);
    model.password = password;

    return new Promise((resolve, reject) => {
    if(model.password) resolve(model.password); 
    else reject(model)
   })
})()
.then((a) =>{
//handling code
})
.catch((a) => {
//handling code
})