Angular forEach 等待所有承诺完成?

Angular forEach wait until all promises are complete?

我正在执行一个 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:

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