【问题标题】:Async function call in if/else not returning valueif/else 中的异步函数调用不返回值
【发布时间】:2019-01-08 21:30:07
【问题描述】:

我一直在尝试在 if/else 中提取异步值,我已经解决了一些错误,但以下是返回空括号:

router.post('/api/shill', async (req, res) => {
  let checkIdLength = req.body.Id;
  let checkIP = validateIP(req.body.Ip);
  let checkPort = Number.isInteger(req.body.Port);
  console.log(req.body.Id);
  if (checkIdLength.length != 66 || checkIP != true || checkPort != true || typeof req.body.Wumbo != "boolean") {
    res.status(400).send('Invalid value(s) detected');
  }
  else try {
      challengeInvoice = getInvoice();
      res.status(200).send(challengeInvoice);
  } catch (e) {console.log(e)}
})

async function getInvoice() {
  await lnd.addInvoice({}, (err, res) => {return res}); 
}

fwiw,lnd.addInvoice 绑定到 grpc 调用

【问题讨论】:

  • getInvoice 不返回任何内容。

标签: node.js grpc


【解决方案1】:

您可以对异步数据使用 Promise。

 try {
      getInvoice().then(challengeInvoice => {
           res.status(200).send(challengeInvoice);
       })
  } catch (e) {console.log(e)}

然后

    function getInvoice() {
        return new Promise( (resolve, reject) => {
          lnd.addInvoice({}, (err, result) => {
            if(err) {
               reject(err);
            }
            else{
              resolve(result)
            }
         }); 
       });
    }

【讨论】:

  • 谢谢你,我能够按照这个建议让事情顺利进行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-01-03
  • 2015-08-24
  • 1970-01-01
  • 1970-01-01
  • 2023-04-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多