假设您有以下代码:
var callNo1 = $http(...).then(function (response1) {
var callNo2 = $http(...).then(function (response2) {
return [response1.data, response2.data];
});
return callNo2;
}).then(function (result) {
console.log(result);
});
由于 callNo2
是一个 promise ,[response1.data, response2.data]
数组将被记录到控制台。我想要实现的是获取对 callNo2
Promise 的引用。所以我的问题是:有没有办法通过 return 语句获取对内部 Promise 的引用,以便可以通过 then 参数访问它。
附注
以下行为将被视为作弊:
var callNo1 = $http(...).then(function (response1) {
var callNo2 = $http(...).then(function (response2) {
return [response1.data, response2.data];
});
return { callNo2: callNo2 };
}).then(function (result) {
console.log(['Do whatever required with result.callNo2', result.callNo2]);
});
最佳答案
为此使用回调函数。看看:
function call1(callback){
return $http(...).then(function (response1) {
var callNo2 = $http(...).then(function (response2) {
callback(response1.data, response2.data);
});
});
}
function calling(){
call1(function(data1, data2){
console.log(data1, data2);
})
}
在call1的then函数中,运行call2并返回promise。当 call2 完成时,回调被调用。
关于javascript - 返回一个 Promise,而不是用 Angular 的 $q.then() 来解决它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33175707/