【问题标题】:Async function returns promise after .thenAsync 函数在 .then 之后返回 Promise
【发布时间】:2022-01-18 07:27:37
【问题描述】:

在我的代码中,我有一个返回承诺的异步函数。我知道之前有人问过这个问题,但是没有一个解决方案有效。

const fetch = require('node-fetch');
async function getData() {
  const response = await fetch(url);
  return (await response.json());
}
getData().then( // wait until data fetched is finished
  console.log(getData())
)

提前谢谢你

【问题讨论】:

  • 究竟是什么不工作?期望的结果是什么?
  • 你还没有问过问题。我猜你想要getData().then(console.log) 或getData().then(data => console.log(data))。
  • @WaisKamal 我正在尝试在函数之外使用响应
  • then 函数将 可调用函数 作为参数,请参阅 developer.mozilla.org/de/docs/Web/JavaScript/Reference/… 您的示例与 this 完全相同,但您没有通过一个可调用函数但一个值(console.log() 的返回)。

标签: javascript asynchronous promise node-fetch


【解决方案1】:

我认为您只是对 .then() 回调的语法有点困惑。

const fetch = require('node-fetch');
async function getData() {
  const response = await fetch(url);
  return (await response.json());
}
getData().then(data => { // Notice the change here
  console.log(data)

  // Now within this block, "data" is a completely normal variable
  // use it as you wish
})

这个答案与 Guerric 的含义相似,但希望以更适合初学者的方式呈现 :)

【讨论】:

    【解决方案2】:

    删除无用的await,只需将console.log 的引用作为Promise 回调传递:

    const fetch = require('node-fetch');
    
    async function getData() {
      const response = await fetch(url);
      return response.json();
    }
    
    getData().then(console.log);
    

    如果您在getData 中没有更多控制流,您可能根本不需要async/await:

    const fetch = require('node-fetch');
    
    function getData() {
      return fetch(url).then(x => x.json());
    }
    
    getData().then(console.log);
    

    【讨论】:

    • 这会记录值。但是,我试图将其设置为变量。有没有办法这样做?抱歉,如果这是一个愚蠢的问题,我对 javascript 还很陌生
    • @Arjinoodles 在不使外部上下文异步的情况下,无法将值从回调内部移动到回调外部。
    • 试图“将变量从函数中取出”通常是一种反模式。在 JavaScript 中编写异步代码时,您会编写一系列异步操作,这会导致最终的“副作用”,例如填充 HTTP 响应、写入文件或其他任何东西。你应该能够在不尝试的情况下实现你想要的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-01
    • 1970-01-01
    • 2018-03-27
    • 2021-05-15
    • 2016-02-14
    • 2021-03-17
    • 2020-04-09
    相关资源
    最近更新 更多