简体   繁体   中英

How to return a json from Fetch API call

My code looks like this

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)

output

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
}

Last console statement should be showing the json which I want to pass down to my express router. But I don't get the desired output.

Reason why I used setInterval was because it does not return a promise. I want to get the cities json and pass it down to my express router.

What I did without setInterval

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

this cities object returned a promise. But I need a proper json. What can I use or do here to?

SetInterval or say the polling approach is not a good idea to go with. That is sort of anti pattern when it comes to this sort of async handling.

You may go with async/await or promises as demonstrated below:

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

or

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM