gpt4 book ai didi

angularjs - 如何实现等待多个异步请求的promise?

转载 作者:行者123 更新时间:2023-12-02 22:35:50 26 4
gpt4 key购买 nike

我们使用 REST API,其中一项功能允许用户对对象进行批量编辑,每个对象都需要一个 PUT 请求来编辑所述对象。现在我们做

angular.foreach(objects, function(data) {
restangular.one('user', user.id).one(object).put();
});
angular.updateInfo('user');

这里的问题是 updateInfo 调用与 PUT 调用异步发生,因此新用户信息并不总是完整/正确。能不能有类似的东西。

var promise = restangular.one('user', user.id);
angular.foreach(objects, function(data) {
promise.one(object).put();
});
promise.then(function (data) {
angular.updateInfo('user');
});

谢谢:)

最佳答案

是的,您可以做到这一点,但它并不像您编写的那么简单

我假设每个put都会给你一个 promise (我从未使用过restangular)。您要做的是创建一个 promise 列表,然后使用 $q.all .

注意请务必将 $q 注入(inject)您的 Controller /服务。

// Initialise an array.
var promises = [];

angular.foreach(objects, function(data) {
// Add the `put` to the array of promises we need to complete.
promises.push(restangular.one('user', user.id).one(object).put());
});

// combine all the promises into one single one that resolves when
// they are all complete:
$q.all(promises)

// When all are complete:
.then( function(resultArray){

// An array of results from the promises is passed
var resultFromFirstPromise = resultArray[0];

// Do whatever you want here.
angular.updateInfo('user');

});

关于angularjs - 如何实现等待多个异步请求的promise?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22766443/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com