[英]Pass the result of getJSON in `then` to next `then`?
以下代码有两个then()
。 第一个then()
有一个$.getJson()
then()
。 如何将$.getJson()
的结果传递给第二个then()
的参数x
?
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
});
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
是异步的,因此您需要返回该函数的执行,以便将其异步执行返回到下一个链接方法。
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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.