0

I try to nest Ajax requests and return a whole array of results.

I have a first API call and I need to do do other requests according to the first result.

The order is the following:

  1. First API call
  2. Loop on results and for each result : do API2 call
  3. return an array of each element : [{Result1-item, Result2-item})

This is

function getVideos () {
    return $.ajax({
        url: 'URL1'
    })
        .then(function (list) {
            let videos = [];

            list.videos.function(video) {
                return $.ajax({
                    url: video.url_id
                })
                    .done(function (videoInfo) {
                        videos.push({video: stream, videoInfo: videoInfo})
                    });
            })
        })
        .done(function (allResult) {
            return allResult;
        });
}

The calls are doing great but I don't get how to gather the video + video infos in the same array

What is missing ?

Alvaro Castro
  • 811
  • 1
  • 9
  • 26
TLd
  • 602
  • 8
  • 23
  • If you need more calls to be returned as array, use [`Promise.all([array of promises])`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all) `.then(values => { /* here values are an array of responses */})`. – tao Jul 31 '18 at 13:03
  • 1
    For nested calls you either need to utilise promises (as above), or have a single callback that's executed when all calls have completed (successful or not). You can't just `return` values from ajax calls as they're asynchronous. – Reinstate Monica Cellio Jul 31 '18 at 13:07
  • What is `list.videos`? – Reinstate Monica Cellio Jul 31 '18 at 13:16
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Liam Jul 31 '18 at 13:18
  • @Liam I think this question just needs some guidance as OP is already using a promise, prior to their issue. The comment above about `Promise.all()` is more relevant than that link. – Reinstate Monica Cellio Jul 31 '18 at 13:21

0 Answers0