How to use the data in Promise & Ajax

I use Promise + ajax load data to my page.

function $myAjax(url, callback) {
   let p = new Promise(function(resolve, reject) {
       $.ajax({
           url: url,
           method: "GET",
           data: "data",
           async:false, 
           cache: false,
           success: function(resp) {
              callback(resp);
              resolve();
           },
           failure: function(xhr) {
              reject();
           }
      });
 });
 return p;
}

$myAjax('api/2006.json', function(resp1){
       mapRender('svg1',resp1,'#b4cdff');
}).then(function() {
       return $myAjax('api/2010.json', function(resp2) {
           mapRender('svg2',resp2,'#b4cdff');
       }); 
}).then(function() {
         //...  and so on
})

But I have problem to get out the resp1 and resp2 from this function, except the mapRender I need the resp1 & resp2 to do something, and the "something" is not suitable inside the $myAjax.

I try to push the resp in array.

$myAjax('api/2006.json', function(resp1) {
         array.push(resp1)
         mapRender('svg1',resp1,'#b4cdff');
})
console.log(array)

console.log(array) => show the data, but with a icon "value below was evaluated just now"

console.log(array[0]) => undefined

What's wrong with it? And How can I get the resp form the $myAjax ?

1 answer

  • answered 2018-11-08 09:42 charlietfl

    A far more efficient way to do this would be use the $.ajax promise itself along with Promise.all() where you would have access to all the responses

    var svgData =[
       {url:'api/2006.json', selector: 'svg1'},
       {url:'api/2010.json', selector: 'svg2'}
    ];
    
    var promises = svgData.map(function(item) {
      // return the ajax promise
      return $.getJSON(item.url).then(function(res) {
        // add the data to svgData object
        item.data = res;
    
      })
    });
    
    Promise.all(promises).then(function() {
      svgData.forEach(function(item) {
        // do what you need with each item here
        mapRender(item.selector, item.data, '#b4cdff');
      });
    }).catch(function(err) {
      alert('Something went wrong with one of the requests');
    })