0

I'm doing a forEach loop and that makes an API call to Cloudinary, and I'm building an array with the response data.

Once the data is collected, I need to send it to some other API.

How do I wait on the promises getting resolved and the data collected before sending the data out?

Here is my code:

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
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Nathan
  • 7,627
  • 11
  • 46
  • 80

1 Answers1

1

What you need here is $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
JLRishe
  • 99,490
  • 19
  • 131
  • 169