【问题标题】:Javascript node-fetch synchronous fetchJavascript节点获取同步获取
【发布时间】:2019-02-08 07:01:18
【问题描述】:

我正在尝试使用 node-fetch 和 nodejs 对我的个人 api 进行 api 调用。我希望能够在其中定期同步更新某些值,因为在幕后我的数据库会更新/更改。我知道存在 async 和 await ,但是通过谷歌搜索,我仍然不太了解它们或它们如何与 fetch 请求交互。

这是我正在尝试使用的一些示例代码,但仍然只是未定义的日志

const fetch = require('node-fetch');
const url = 'http://example.com';
let logs;

example();
console.log(logs);
async function example(){
    //Do things here
    logs = await retrieveLogs();
    //Do more things here
}

async function retrieveLogs(){
    await fetch(url)
    .then(res => res.json())
    .then(json => {return json})
    .catch(e => console.log(e))
}

【问题讨论】:

  • await example();
  • .then(json => {return json}) 这行毫无意义。只需将其删除。
  • 感谢您的帮助!这两件事都有些正确,但不是全部答案,因为我仍然需要像 Ali 指出的那样返回 fetch
  • 请注意,使用asyncawait 确实不会使您的操作同步。它只是语法糖,可以使您的代码更优雅并像同步一样显示它。动作在幕后仍然是异步的。

标签: javascript async-await synchronous node-fetch


【解决方案1】:

我认为您需要像这样返回retrieveLogs 函数结果:

async function retrieveLogs(){
    return await fetch(url)
    .then(res => res.json())
}

【讨论】:

  • 这样做很有意义,因为 await 正在寻找要解决的承诺。我没有意识到你可以返回一个 await 并认为我需要第二个 .then 来实际获取返回的数据。我还犯了一个严重错误,因为我认为 skyboyer 指出我必须等待原始函数调用(可能使用匿名函数),否则错误放置的 console.log 会在 example() 完成之前触发。谢谢!
  • 实际上,经过进一步检查,我似乎不需要该函数是异步的,也不需要等待获取。我假设 example() 中第一次调用的 await 处理了这个?
  • Fetch 函数是一个原生的 async 函数,如果你不想使用 await 语法,你可以在 fetch 之后调用 then 来获取值。
  • 问题:“如何同步”。答案:“这是异步的方法”。 Insta-downvote。
【解决方案2】:

正如 Ali Torki 在评论中所说,fetch() 是一个异步函数,无论如何都不能“进行”同步。如果您必须与 HTTP 同步获取(例如,因为您必须在不能异步的属性 getter 中使用它),那么您必须使用不同的 HTTP 客户端,句号。

【讨论】:

    【解决方案3】:
    npm install sync-fetch
    

    围绕 Fetch API 的同步包装器。在后台使用 node-fetch,也用于一些输入解析代码和测试用例。

    https://www.npmjs.com/package/sync-fetch

    【讨论】:

      【解决方案4】:

      使用立即调用的异步函数表达式:

      (async () => {
        try {
      
          const response = await fetch('http://example.com')
          const json = await response.json()
      
        } catch (error) {
          console.log(error);
        }
      })();
      

      【讨论】:

        猜你喜欢
        • 2011-02-09
        • 1970-01-01
        • 2017-09-06
        • 1970-01-01
        • 2013-05-04
        • 2017-09-29
        • 2013-04-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多