Angular forEach 等到所有承诺都完成?
Posted
技术标签:
【中文标题】Angular forEach 等到所有承诺都完成?【英文标题】:Angular forEach wait until all promises are complete? 【发布时间】:2015-04-24 14:19:16 【问题描述】:我正在执行一个 forEach 循环,它对 Cloudinary 进行 API 调用,并且我正在使用响应数据构建一个数组。
收集完数据后,我需要将其发送到其他 API。
在发送数据之前如何等待承诺得到解决和收集的数据?
这是我的代码:
app.controller 'ProductImageUploaderController', ($upload, $routeParams, Product) ->
$routeParams.photos = []
@startUpload = ->
@files.forEach (file) ->
upload = $upload.upload(
url: 'https://api.cloudinary.com/v1_1/' + $.cloudinary.config().cloud_name + '/upload'
fields:
upload_preset: $.cloudinary.config().upload_preset
tags: 'dev'
folder: 'dev'
file: file
)
upload.success (data) ->
$routeParams.photos.push(file)
# Once the $routeParams.photos array is built, this is when I'd like to pass the data on.
return
【问题讨论】:
$q.all(): docs.angularjs.org/api/ng/service/$q#all $q promise with Underscore _each的可能重复 以下 JLRishe 提供的最佳答案。一个例子总是有帮助的。 【参考方案1】:你需要的是$q.all
:
app.controller 'ProductImageUploaderController', ($upload, $routeParams, Product, $q) ->
$routeParams.photos = []
@startUpload = ->
pFiles = @files.map (file) ->
$upload.upload(
url: 'https://api.cloudinary.com/v1_1/' + $.cloudinary.config().cloud_name + '/upload'
fields:
upload_preset: $.cloudinary.config().upload_preset
tags: 'dev'
folder: 'dev'
file: file
).then (response) -> file
$q.all(pFiles).then (uploadedFiles) ->
$routeParams.photos = uploadedFiles
#all files have been uploaded. use tham as you wish
return
【讨论】:
以上是关于Angular forEach 等到所有承诺都完成?的主要内容,如果未能解决你的问题,请参考以下文章