0

I have a weird Promise behavior which returns the incorrect value.

var years = []

$.getJSON('https://omdbapi.com?t=titanic&apikey=thewdb')
.then(function(movie){  
  years.push(movie.Year)
  return $.getJSON('https://omdbapi.com?t=shrek&apikey=thewdb')
})
.then(function(movie){  
  years.push(movie.Year)  
  console.log(years) // ["1997", "2001"]
})

console.log(years) // [] return at the beginning
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

The empty array is being returned in the first place is from the end of the code - which is weird to me. Can you have to explain this? Thanks,

Dale Nguyen
  • 1,930
  • 3
  • 24
  • 37
  • getJson is asynchronous. console.log will happen before the getJSON resolves the request and processes the response. The whole point of promises is for asynchronous logic that will finish *sometime* in the future. Attaching callbacks to the promise allow you to handle the response *when* it gets it. It doesn't stop your code from running until that point. – Taplar Dec 07 '17 at 18:38
  • Ajax is **asynchronous**...the last `log()` occurs before the requests complete – charlietfl Dec 07 '17 at 18:38
  • Thanks Taplar and charlietfl. I will read more about Asynchronous then. – Dale Nguyen Dec 07 '17 at 18:40
  • @DaleNguyen If the code ran in chronological order from top to bottom, why would you need Promises in the first place? –  Dec 07 '17 at 18:41
  • http://learn.jquery.com/ajax/ is a decent place to get some intro information. – Taplar Dec 07 '17 at 18:41
  • This is a classic problem of **asynchronous** behavior. The request to the api is asynchronous. Your code will not stop and wait for it to return some response. Because of that, your script keeps executing and will console log years as an empty list because that is exactly what it is. After the promise has resolved and you got a response, then it will update that variable. That is the reason why in the end of your promise chain, you can see the actual value of years, which should include two elements. – nbkhope Dec 07 '17 at 18:41

1 Answers1

0

The reason the first console.log prints [] is because the $.getJSON and .then() functions have not executed yet. This is known as asynchronous code meaning that things may not execute in the order they appear in the code.

L Bahr
  • 2,723
  • 3
  • 22
  • 25