Angular forEach等到所有承诺完成?

时间:2015-02-23 09:42:04

标签: angularjs coffeescript promise angular-promise cloudinary

我正在做一个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

1 个答案:

答案 0 :(得分: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