var app = angular.module('app', []); app.controller('appctrl', ['$http', '$q', function($http, $q) { function aaa(id) { var deferferred = $q.defer(); $http({ method: 'get', url: 's' + id + '.html' }).then(function(res) { deferred.resolve(1); }) return deferred.promise; } var b = [0,1, 2, 3, 4, 5, 6, 7, 8, 9]; var c = []; for (var i = 0; i < b.length; i++) { var promise = aaa(b[i]); promise.then(function(res) { c.push(res); }) } console.log(c) }])请问,如何让for循环中的promise全部完成后,取到所有的res,保存在c里?
1 回答

慕勒3428872
TA贡献1848条经验 获得超6个赞
for 循环是马上走下去的。所以要跳出循环等promise执行完了才玩下走。
了解下 async中的await 可以在中for循环使用await
当js遇到await会暂时跳出循环。等await执行完了。才继续往下执行。
如果有多个await 会一个个的执行。
async function aaa() {
////
for (var i = 0; i < b.length; i++) {
await fun();//要循环执行的函数
}
}
添加回答
举报
0/150
提交
取消