Home > other >  Promise always keep pending status
Promise always keep pending status

Time:01-22

Hi I'm testing this JS function using OpenWeatherMap API, but when I fetch the request the promise jumps to .then() with pending status, so when I try to apply response => response.json() it's showing this error SyntaxError: Unexpected token < in JSON at position 0

Here's my code:

function onSearch(city){
    fetch(`api.openweathermap.org/data/2.5/weather?q=London&appid=${ApiKey}&units=metric`)
      .then(response => response.json())
      .then(data => {
        console.log(data)
        if(data.main !== undefined){
          const city = {
            min: Math.round(data.main.temp_min),
            max: Math.round(data.main.temp_max),
            id: data.id,
            img: data.weather[0].icon,
            wind: data.wind.speed,
            temp: data.main.temp,
            name: data.name,
            logitude: data.coord.lon,
            latitude: data.coord.lat
          };
        }
      })
      .catch(e => console.log(e))
  }

Any ideas on how to solve this issue?

CodePudding user response:

Its because your function onSearch finishes executing while you call to api havent received results, so solve this you can wait till the results are returned and then finish executing function just with few tricks

change your function to async as below

async function onSearch(city) {

  await fetch(`api.openweathermap.org/data/2.5/weather?q=London&appid=${ApiKey}&units=metric`)
      .then(response => response.json())
      .then(data => {
        console.log(data)
        if(data.main !== undefined){
          const city = {
            min: Math.round(data.main.temp_min),
            max: Math.round(data.main.temp_max),
            id: data.id,
            img: data.weather[0].icon,
            wind: data.wind.speed,
            temp: data.main.temp,
            name: data.name,
            logitude: data.coord.lon,
            latitude: data.coord.lat
          };
        }
      })
      .catch(e => console.log(e))
}

and on the calling function never to use await key word as below

async function Calling(){

 await onSearch('city name');

}

CodePudding user response:

Try this:

function onSearch(city){
  fetch(`api.openweathermap.org/data/2.5/weather?q=${city}&appid=${ApiKey}&units=metric`)
    .then((response) => {
      response.json().then((data) => {
      console.log(data)
      if(data.main !== undefined){
        const city = {
          min: Math.round(data.main.temp_min),
          max: Math.round(data.main.temp_max),
          id: data.id,
          img: data.weather[0].icon,
          wind: data.wind.speed,
          temp: data.main.temp,
          name: data.name,
          logitude: data.coord.lon,
          latitude: data.coord.lat
        };
      }
    })
    .catch(e => console.log(e))})
}
  •  Tags:  
  • Related