1

Iam pretty new to JS and I have a problem with extracting data from an async/await function. The following does work and it prints the correct answer which is a number to the console.

fetchData = userData.getPom().then(res => { console.log(res) })

But when I try to extract the res outside of the scope of the function it doesnt work, it still prints points as 0.

var points = 0
fetchData = userData.getPom().then(res => { points += res })
console.log(points)

What am I doing wrong? Thanks in advance

printscreen of both console.logs:

enter image description here

mpromonet
  • 11,326
  • 43
  • 62
  • 91
Jeek
  • 21
  • 5
  • 1
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – old greg May 06 '21 at 10:20

3 Answers3

2

You need to use await instead of then

async myfunction () => {     
    var points = 0
    fetchData = await userData.getPom()
    points += fetchData
    console.log(points);
    return points;
}
0

Try this:

let points = 0
userData.getPom().then(res => points += res).then(points => {
  console.log(points)
  // Continue your logic here...
})

or with newer await/async:

async function calcPoints() {
  let points = 0
  let res = await userData.getPom()
  points += res
  console.log(points)
  // Continue your logic here...
  
  return points
}

Your problem is related to Asynchronous JavaScript. In your original code it will instantly console.log(points) instead of waiting for the then operations to be done. So the result will be 0. You can either put another then behind it or use the newer await and async technique. (It was invented to get rid of the not good readable then). Check some tutorials about this topic.

Lars Flieger
  • 2,421
  • 1
  • 12
  • 34
0

You're printing points to the console before the callback function in then has been executed.

The order of execution is (probably, but not guaranteed) to be:

  • create new fetch promise
  • fetch starts running in the 'background'
  • print out the value of points
  • at some point, fetch finishes and we increment points

The fetch operation may or may not finish before you get to the line where you print the value of points. If you get indeterminate results, this is why.

Essentially for your use case, you need to wait until the request is finished before using/accessing the returned value.

There's two ways to approach fixing this:

Print points in the callback:

fetchData = userData.getPom().then(res => { 
  console.log(res)
})

Await the promise before printing

async function printPoints() {
  const points = await userData.getPom()
  console.log(points)
}
printPoints()

Note for the second, you can only (as of mid 2021, without using special flags or transpilation which may be a bit advanced) use await in an async function, so we have to wrap this.

old greg
  • 799
  • 8
  • 19