-1

The following code has two then(). There is a $.getJson() in the first then(). How to pass the result of $.getJson() to the parameter x of the second then()?

  MyPromise
  .then(function (i) {
    instance = i;
    var cookie;
    $.getJSON('http://localhost:5000/api/cookie/'+i.address+'/articleid/'+id, function(x){
      cookie = x;
    });
    console.log('[' + cookie + ']'); // undefined, it will get right value if put the two lines in .done() but then cannot return the cookie to next then().
    return cookie;
  })

  .then(x => {
    console.log("need to get cookie here: "+x); // x is undefined 
  });    
ca9163d9
  • 27,283
  • 64
  • 210
  • 413
  • Possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/q/23667086/218196) – Felix Kling Feb 12 '18 at 05:42

2 Answers2

1
MyPromise
.then(function (i) {
  instance = i;
  return $.getJSON('http://localhost:5000/api/cookie/'+i.address+'/articleid/'+id);
})
.then(x => {
  console.log("need to get cookie here: "+x); // x is undefined 
});    

Since $.getJSON is asynchronous, you need to return the execution of that function in order to return its asynchronous execution to the next chained method.

Prusprus
  • 7,987
  • 9
  • 42
  • 57
1

getJSON returns a promise like value so you don't need the callback. Accepted answer is confusing and suggests that callback and return cookie is needed.

MyPromise
.then(function (i) {
  //in a .then you can return a new promise like value
  return $.getJSON('http://localhost:5000/api/cookie/'+i.address+'/articleid/'+id);
})
.then(x => {
  //you returned a promise like value before so here you'll get the
  //  resolve of that promise.
  console.log("need to get cookie here: "+x);
})
//since jQuery 3 the promise like are more compatible with native promises
//  you can use catch
.catch(err=>console.warn("something went wrong:",err));  
HMR
  • 37,593
  • 24
  • 91
  • 160