【问题标题】:calling an await within a then在 then 中调用 await
【发布时间】:2020-12-17 23:56:17
【问题描述】:

我有以下代码...

  run(cert).then( serverPop => {
    const popInt = parseInt(serverPop);
    console.log("The new pop resport is: " + serverPop);
    if (oldPop < popInt) {
      let addDB = "https://www.website.com/u.php?o=" + oldPop + "&c=" + cert + "&n=" + popInt;
      const popIntoDoResponse = await axios.get(addDB); //error here
      res.json({
        ack: "success",
        message: "POP IS UPDATED",
        pop: popInt,
        serverResponse: popIntoDoResponse.data
      });
    } else {
      res.json({
        ack: "success",
        message: "POP IS THE SAME",
        pop: popInt
      });
    }

我在日志中得到以下指向await

await 只在 async 函数中有效

【问题讨论】:

    标签: node.js promise async-await


    【解决方案1】:

    你在 then 方法中错过了async

    run(cert).then(async (serverPop) => { // add `async`
        const popInt = parseInt(serverPop);
        console.log("The new pop resport is: " + serverPop);
        if (oldPop < popInt) {
          let addDB = "https://www.website.com/u.php?o=" + oldPop + "&c=" + cert + "&n=" + popInt;
          const popIntoDoResponse = await axios.get(addDB); //error here
          res.json({
            ack: "success",
            message: "POP IS UPDATED",
            pop: popInt,
            serverResponse: popIntoDoResponse.data
          });
        } else {
          res.json({
            ack: "success",
            message: "POP IS THE SAME",
            pop: popInt
          });
        }
    

    【讨论】:

    • 啊,谢谢!奇迹般有效。我能接受时我会接受!
    猜你喜欢
    • 2018-06-18
    • 1970-01-01
    • 1970-01-01
    • 2019-05-14
    • 2019-07-27
    • 1970-01-01
    • 2022-01-19
    • 2017-04-28
    • 1970-01-01
    相关资源
    最近更新 更多