将`then`中的getJSON结果传递给下一个`then`?

时间:2018-02-12 00:50:49

标签: javascript ecmascript-6 promise

以下代码有两个then()。第一个$.getJson()中有一个then()。如何将$.getJson()的结果传递给第二个x的参数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 
  });    

2 个答案:

答案 0 :(得分: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 
});    

由于$.getJSON是异步的,因此需要返回该函数的执行,以便将其异步执行返回到下一个链式方法。

答案 1 :(得分:1)

getJSON返回一个类似值的promise,因此您不需要回调。接受的答案令人困惑,并建议回调和return cookie是必需的。

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));