首页 > 解决方案 > 如何使用 Promise & Ajax 中的数据

问题描述

我使用 Promise + ajax 将数据加载到我的页面。

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
})

但是我有问题要从这个函数中取出resp1and resp2,除了mapRender我需要 resp1 和 resp2 来做某事,而“某事”不适合在$myAjax.

我尝试推入resp数组。

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

console.log(array)=> 显示数据,但带有一个图标“下面的值刚刚被评估”

console.log(array[0])=> 未定义

它出什么问题了?我怎样才能得到resp表格$myAjax

标签: javascriptjqueryajaxpromise

解决方案


一种更有效的方法是使用$.ajaxPromise 本身以及Promise.all()您可以访问所有响应的位置

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');
})

推荐阅读