【问题标题】:How to return a json from Fetch API call如何从 Fetch API 调用返回 json
【发布时间】:2021-11-22 02:22:01
【问题描述】:

我的代码是这样的

const TIME_REPEAT = 62e5

const getCities = () =>
        fetch('mocky url')
            .then(response => {
                console.log(response)
                return response.json()
            })
            .then(json => {
                console.log('hello json:', json)
                return json
            })

const cities = setInterval(getCities, TIME_REPEAT)

console.log('hello cities:', cities)

输出

hello cities: Timeout {
  _idleTimeout: 6200000,
  _idlePrev: [TimersList],
  _idleNext: [TimersList],
  _idleStart: 4013,
  _onTimeout: [Function: getCities],
  _timerArgs: undefined,
  _repeat: 6200000,
  _destroyed: false,
  [Symbol(refed)]: true,
  [Symbol(asyncId)]: 14375,
  [Symbol(triggerId)]: 0
}

最后一个控制台语句应该显示我想要传递给我的快速路由器的 json。但我没有得到想要的输出。

我使用 setInterval 的原因是它不返回承诺。我想获取城市 json 并将其传递给我的快速路由器。

没有 setInterval 我做了什么

const cities = fetch('mocky url')
        .then(response => {
            console.log(response)
            return response.json()
        })
        .then(json => {
            console.log('hello json:', json)
            return json
        })

这个城市对象返回了一个承诺。但我需要一个合适的json。我可以在这里使用或做什么?

【问题讨论】:

  • 或者你可以使用async/await来减少代码和减少头痛

标签: javascript json express setinterval fetch-api


【解决方案1】:

SetInterval 或者说轮询方法不是一个好主意。当涉及到这种异步处理时,这是一种反模式。

您可以使用 async/await 或 Promise,如下所示:

 const exec = async function(){
    const cities = await getCities();
    console.log(cities)
 }
 exec()

getCities.then((cities)=>{
  console.log(cities)
})

【讨论】:

    猜你喜欢
    • 2017-09-13
    • 2019-11-23
    • 2017-10-01
    • 2020-02-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-28
    • 2017-09-05
    相关资源
    最近更新 更多