javascript - 如何使用 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
})
但是我有问题要从这个函数中取出resp1
and 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
?
解决方案
一种更有效的方法是使用$.ajax
Promise 本身以及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');
})
推荐阅读
- google-maps - 谷歌地图会向开发者公开交通数据的网络 API 吗?
- php - Visual Studio Code 主题编辑 PHP
- lucene - Lucene Query 的 extractTerms 的替代方案是什么?
- ios - 在哪里删除 Xamarin iOS 中的通知观察者?
- postgresql - 当达到单页的列限制时,如何在下一页上打印时动态地在 ireport 上水平打印?
- dart - Dart / AngularDart - 如何创建图表/流程图?
- ansible - 过滤器:当参数是字符串 v/s 变量时的不同行为
- android - PathEffect 改变路径的长度
- python - 'pip install --upgrade pip' 的语法错误无效
- security - 为内部应用程序实施 SSO 身份验证的最佳实践,例如气流仪表板、apache spark 笔记本等