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) {
           url: url,
           method: "GET",
           data: "data",
           cache: false,
           success: function(resp) {
           failure: function(xhr) {
 return p;

$myAjax('api/2006.json', function(resp1){
}).then(function() {
       return $myAjax('api/2010.json', function(resp2) {
}).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) {

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 = {
      // return the ajax promise
      return $.getJSON(item.url).then(function(res) {
        // add the data to svgData object = res;
    Promise.all(promises).then(function() {
      svgData.forEach(function(item) {
        // do what you need with each item here
        mapRender(item.selector,, '#b4cdff');
    }).catch(function(err) {
      alert('Something went wrong with one of the requests');