【问题标题】:using promises and async for protobufjs loadcall使用 Promise 和 async 进行 protobufjs 加载调用
【发布时间】:2020-02-22 21:43:31
【问题描述】:

我正在尝试找出重写以下代码的最佳方法:

var api = function(id, contract) {
  var callback = function (error, root) {
    if (error)
      throw error;
    var by = Buffer.from(contract,'base64')
    var es = root.lookupType("Contract")
    var esMsg = es.decode(by)
    var esBytes = es.encode(esMsg).finish()
    signature = id.sign(esBytes).toString('base64')
  }
  return new Promise((resolve, reject) => {
     protobuf.load("contract.proto", callback)
  })
}
var signContract = async(privateKey, contract) => {
  let signature
  var id = await crypto.keys.unmarshalPrivateKey(Buffer.from(privateKey, 'base64'))
  result = await api(id,contract,signature)
}

function getSessionSignature (hash, time) {
  return config.id + ":" + hash + ":" + time
}
module.exports = configure(({ ky }) => {
  return async function * signbatch (input, options) {

    var contracts = input.Contracts

      for (var i = 0 ; i < contracts.length ; i++) {
        contracts[i].contract = await signContract(config.PrivKey, contracts[i].contract)
      }

      //add signed contracts to the searchParams
      searchParams.append("arg", JSON.stringify(contracts))

      let res
      res = await ky.post('storage/upload/signbatch', {
        searchParams
      }).json()
      yield JSON.stringify({})
    } else {
      yield JSON.stringify({error:"Private key not found"})
    }
  }
})

我的问题是如何编写签名异步代码以将 privateKey 和 contract 变量传递给 api var 函数并将签名返回给要分配给 contracts[i].contract 的结果变量?请注意,id.sign(..) 函数是回调函数内部的 Promise。

【问题讨论】:

  • var signature = id.sign(escrowBytes) ... 是一个 Promise,那么如何将签名的值返回给 signBatch 呢?

标签: javascript protobuf.js


【解决方案1】:

您需要在 api 函数中解析承诺,文档建议您可以在此处使用单参数变体,例如

var root = await protobuf.load("contract.proto");
... // (The code you currently by have in 'callback'
return signature;

由于生成器是async,yield 将发出一个Promise,您可以(显然)使用.then 或await 处理它

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-15
    • 2017-02-25
    • 1970-01-01
    • 1970-01-01
    • 2021-05-13
    • 2016-02-26
    • 2018-03-29
    相关资源
    最近更新 更多