【问题标题】:issue with promise Node.js承诺 Node.js 的问题
【发布时间】:2020-06-14 02:20:34
【问题描述】:

我一直在努力解决这个问题,这太令人困惑了,所以我想我会问。

var listenKey = "";

const createListenKey = async () => {
  await axios({
    url: "/api/v3/userDataStream",
    method: "POST",
    baseURL: "https://api.binance.com",
    headers: {
      "X-MBX-APIKEY":
        "H48w9CLuTtTi955qWjcjjEKhh0Ogb3jnnluYucXXXXXXXXXXXXXXXX",
    },
  }).then((response) => {
    var key = response.data.listenKey;
    console.log(key, "created");
    return key;
  });
};

listenKey = createListenKey();

listenKey.then((key) => {
  console.log(key);
});

console.log 在最后但一行打印未定义。这是为什么呢?

提前致谢!

【问题讨论】:

  • 因为你没有从createListenKey返回任何东西。你不应该混合使用显式的 promise 和 async-await。
  • 您不会从 createListenKey 函数返回任何内容。调用 await 与返回 Promise 不同。
  • @Lennholm 是对的 +1

标签: javascript asynchronous async-await es6-promise


【解决方案1】:

你没有从异步函数createListenKey返回任何东西

const asynF = async ()=>{


Promise.resolve(1).then(res=>{

 //Simulating response from axios call
 console.log(res)
})

// you are not returning anyting from this function  equivalent of => return ;
}

asynF().then(res=>{
//this would log undefined 
console.log(res)
})

如您所知,异步函数返回一个承诺,您有两个选项可以使外部包装器也成为异步函数,并且只需使用如下所示的等待

const key = await createListenKey(config)

否则

你可以这样做

   return createListenKey(config).then(res=>{

 listenKey = res
})

在不了解上下文的情况下不能说更多。 我是否建议不要将 then 和 async wait 混合在一起

【讨论】:

    【解决方案2】:

    因为createListenKey() 函数不返回任何内容。该函数内的 then 子句中的 return 语句的范围在 then 块中。要从异步函数返回值,您需要执行以下操作。

    const createListenKey = async () => {
      const response = await axios({
        url: "/api/v3/userDataStream",
        method: "POST",
        baseURL: "https://api.binance.com",
        headers: {
          "X-MBX-APIKEY":
            "H48w9CLuTtTi955qWjcjjEKhh0Ogb3jnnluYucXXXXXXXXXXXXXXXX",
        },
      })
    
      var key = response.data.listenKey;
      console.log(key, "created");
      return key;
    };
    

    【讨论】:

    • 当我尝试将返回值分配给函数外部的变量时,它会在从 API 获取数据之前运行。我如何在不使用 IIFE 异步函数的情况下解决这个问题?
    • 那么你能详细说明一下这是什么背景吗?
    • 因此,根据这个答案,要将返回值分配给函数范围之外的变量,我必须像这样使用 IIFE async (async () => { listenKey = await createListenKey(); })();如果我不显示 Promise 除了使用 IIFE 异步之外还有其他方法吗?
    • @KautilyaKondragunta 如果在全局范围内使用异步函数,则需要将其包装在 IIFE 中。 Node.js 14 支持顶级等待,但它还不是 LTS。
    猜你喜欢
    • 2017-05-15
    • 2020-04-03
    • 2017-01-13
    • 2023-03-26
    • 2017-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多