cannot get value from fetch javascript node-fetch

Viewed 59

im trying to get value from this scritp below but it's cant

let doGetVexLastInfo = (url) => {
    fetch(url)
    .then(res => res.json())
    .then(json => {
        let result = 1000 / json.ticker.last;
        return result.toFixed(4);
    });   
}

console.log(doGetVexLastInfo(url))
2 Answers

You should return fetch() to can access "result.toFixed(4)" using .then()

let doGetVexLastInfo = (url) => {
    return fetch(url)
    .then(res => res.json())
    .then(json => {
        let result = 1000 / json.ticker.last;
        return result.toFixed(4);
    });   
}

// with .then()
doGetVexLastInfo(url)
    .then(console.log)
    .catch(console.error)

// with await
(async (){
  const output = await doGetVexLastInfo(url);
  console.log(output)
})();

Fetch is an async call. and here you are trying to mix both async and and a synchronous call together. The correct usage and definition of what you are trying to achieve is as below

let doGetVexLastInfo = (url) => {
    return fetch(url)
          .then(res => res.json())
          .then(json => {
              let result = 1000 / json.ticker.last;
              return Promise.resolve(result.toFixed(4));
           }); 
}

doGetVexLastInfo(url)
    .then(result => console.log(result))

Now the doGetVexLastInfo function returns a promise which when resolved gives the proper result.

Related