简体   繁体   English

解决承诺<pending>

[英]Resolving Promise <pending>

I'm looking to create a simple helper function which returns the hash for a given password using bcrypt but everytime i call the function, it resolves to Promises { <pending> } what am i doing wrong?我正在寻找一个简单的帮助函数,它使用bcrypt返回给定密码的哈希值,但每次我调用该函数时,它都会解析为Promises { <pending> }我做错了什么?

const saltPassword = async (password) => {
    const newHash = await bcrypt.hash(password, saltRounds, (err, hash) => {
        if (err) return err;
        return hash;
    });
    return await newHash;
}

cheers欢呼

You should do something like this你应该做这样的事情

const saltPassword = async (password) => {
  const newHash = await bcrypt.hash(password, saltRounds, (err, hash) => {
    if (err) return err;
    return hash;
  });
  return newHash; // no need to await here
}

// Usage
const pwd = await saltPassword;

You need to return a Promise in order to use await .您需要返回一个 Promise 才能使用await Simply wrap the callback function and call reject if there is an error or resolve if it was successful.简单地包装回调函数并在出现错误时调用拒绝,如果成功则调用resolve。

const saltPasswordAsync = (password, rounds) =>
    new Promise((resolve, reject) => {
      bcrypt.hash(password, rounds, (err, hash) => {
        if (err) reject(err);
        else resolve(hash)
      });
    });


async function doStuff() {
  try {
    const hash = await saltPasswordAsync('bacon', 8);
    console.log('The hash is ', hash);
  } catch (err) {
    console.error('There was an error ', err);
  }
}

doStuff();

Now you can use await to wait on the promise to resolve and use the value.现在您可以使用await等待承诺解析并使用该值。 To catch an error, wrap with a try/catch statement.要捕获错误,请使用 try/catch 语句进行包装。

UPDATE更新

Thomas pointed out that you may not need to wrap the callback in a promise, since bcrypt returns a promise if you do not pass a callback function. Thomas 指出您可能不需要将回调包装在承诺中,因为如果您不传递回调函数,bcrypt 会返回一个承诺。 You could replace the call to saltPasswordAsync above with bycript.hash like so:您可以使用bycript.hash替换上面对saltPasswordAsync的调用, saltPasswordAsync所示:

const hash = await bcrypt.hash('bacon', 8);
console.log('The hash is ', hash);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM