我需要将数据从数据库推送到一个新的数组中,该数组将返回promise对象。我需要打5次电话。所以我这样做。
var items = [];
function setData() {
facilityAPIs.getAllListItems.get({
listName: "Samples"
}).
$promise.then(function(data) {
alert("1");
for (var j = 0; j < data.items.length; j++) {
items.push(data.items[j]);
}
console.log(items);
}).then(function() {
facilityAPIs.getAllListItems.get({
listName: "Controls"
}).
$promise.then(function(data) {
alert("2");
for (var j = 0; j < data.items.length; j++) {
items.push(data.items[j]);
}
console.log(items);
});
}).then(function() {
facilityAPIs.getAllListItems.get({
listName: "FibroBlast"
}).
$promise.then(function(data) {
alert("3");
for (var j = 0; j < data.items.length; j++) {
items.push(data.items[j]);
}
console.log(items);
});
}).then(function() {
facilityAPIs.getAllListItems.get({
listName: "pBMC"
}).
$promise.then(function(data) {
alert("4");
for (var j = 0; j < data.items.length; j++) {
items.push(data.items[j]);
}
console.log(items);
});
}).then(function() {
facilityAPIs.getAllListItems.get({
listName: "iPS Cell Lines"
}).
$promise.then(function(data) {
alert("5");
for (var j = 0; j < data.items.length; j++) {
items.push(data.items[j]);
}
console.log(items);
});
});
}
但如果我想在所有数据都被推入数组后使用items数组,比如调用splitData(items(。我怎么能那样。非常感谢。
是这样的吗?
var items = [];
some_fn(...)
.then(function(data) { [push data to items] })
.then(function() {
some_fn(...).then(function(data) { [push data to items] });
})
.then(function() {
some_fn(...).then(function(data) { [push data to items] });
})
.then(function() {
some_fn(...).then(function(data) { [push data to items] });
})
.then(function() {
some_fn(...).then(function(data) { [push data to items] });
})
.then(function() {
...use items somehow after _all_ data has been pushed to it...
})
如果是这样的话,那么问题就在于这个".then
链"实际上并不是一个链:"顶级.then
"将一个接一个地执行,但在它们中的每一个内部,您将分别启动一个新的异步操作。其中的每一个最终都会将一些数据推送到项目中,但最终结果无法在最后一个".then
"中捕获。
如果你只是简单地将多个"已实现"的回调附加到同一个承诺上,而你没有从它们返回承诺,那么当你的第一个承诺实现时,它们将被一个接一个地执行:
promise
.then(function() { foo; } // will be executed when promise is fulfilled
.then(function() { bar; } // will be executed right after
如果您在回调中运行其他异步操作,并希望创建一个链,则需要从回调返回一个promise:
promise
.then(function() { return promise_foo; } // will be executed when promise is fulfilled
.then(function() { return promise_bar; } // will be executed when promise_foo is fulfilled
(有关详细信息,请参阅规范中的承诺解决程序(
因此,最初的例子可以像这样重组,以创建一个单链:
some_fn(...)
.then(function(data) { [push data to items] })
.then(function() {
return some_fn(...).then(function(data) { [push data to items] });
})
.then(function() {
return some_fn(...).then(function(data) { [push data to items] });
})
.then(function() {
return some_fn(...).then(function(data) { [push data to items] });
})
.then(function() {
return some_fn(...).then(function(data) { [push data to items] });
})
.then(function() {
...all operations have finished, you can use items here...
})