【问题标题】:How to make a blocking call with async/await [duplicate]如何使用 async/await 进行阻塞调用 [重复]
【发布时间】:2019-04-02 23:07:26
【问题描述】:

我怎样才能使这个调用阻塞(例如,使用 async/await)?

testMethod(message) {
    let signature;
    eccrypto.sign(this.privateKey, msg)
        .then(function (sig) {
            console.log("Signature in DER format:", sig);
            signature = sig;
        });
    return signature;
}

我希望 testMethod 返回signature,现在返回(当然)undefined!我一直在玩async/await,但没有成功...

有什么帮助吗?

【问题讨论】:

  • async/await 只是用更好的语法处理 Promise 的方法。他们不会阻止异步代码异步。
  • 一件小事,但您在函数定义中使用了message,但在对eccrypto.sign 的调用中使用了msg。这是故意的吗?这让我想到另一点,你应该始终处理你的错误,如果使用老式的 promise 语法,则使用 .catch(),或者如果使用 async/await 则使用 try/catch

标签: javascript node.js async-await


【解决方案1】:

当然,您可以执行异步/等待。像这样

async testMethod(message) {
    let signature;
    signature = await eccrypto.sign(this.privateKey, msg)
        .then(function (sig) {
            console.log("Signature in DER format:", sig);
            return sig;
        });
    return signature;
}

但它不会阻塞。它的工作方式类似于同步代码,但不一样。请参阅details

【讨论】:

  • 这不是 async/await 的正确语法。
  • 为什么会这样?据我了解,testMethod 是一个类方法
  • 是的,async 部分是正确的,但是第三行应该是signature = await eccrypto.sign(... await 在 async 函数调用之前进行
  • 哦,是的。我的错。谢谢
【解决方案2】:
async testMethod(msg) {
    try {
      const signature = await eccrypto.sign(this.privateKey, msg)
      console.log('Signature in DER format:', signature);
      return signature;
    } catch (e) {
      console.error('Error generating signature', e.message);
    }
}

【讨论】:

  • 此答案因其长度和内容而被标记为低质量。您能否考虑添加一些额外的信息来解释您的答案。
猜你喜欢
  • 2018-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-16
  • 2013-12-25
  • 2016-02-08
相关资源
最近更新 更多