我的AJAX调用是在for循环内部构建的。他们需要按顺序(同步)。我如何链接他们与jQuery?带jQuery的动态AJAX承诺链
13
A
回答
12
:我们可以把返回值在数组例如
var array = ['One', 'Two', 'Three'];
var id = array[0];
var data = getData(id);
for (var i = 1; i < array.length; i++) {
// Or only the last "i" will be used
(function (i) {
data = data.then(function() {
return getData(array[i]);
});
}(i));
}
// Also, see how better the getData can be.
function getData(id) {
return $.ajax({
url: 'http://example.com/' + id,
dataType: 'jsonp',
}).done(function(d) {
var response = d;
console.log(d);
}).fail(function() {
alert('ERROR');
});
}
顺便说一句,如果你使用正确的承诺库,如bluebird,你会使用下面的代码:
var array = ['One', 'Two', 'Three'];
Promise.reduce(array, function(data, id) {
return data.promise.then(function(result) {
return { promise: getData(id), results: data.results.push(result) };
});
}, []).then(function(data) {
console.log(data.results); // yay!
});
function getData(id) {
return Promise.cast($.ajax({
url: 'http://example.com/' + id,
dataType: 'jsonp',
}).done(function(d) {
var response = d;
console.log(d);
}).fail(function() {
alert('ERROR');
}));
}
正如您所看到的,读取/写入的方式更简单。
9
大多数承诺库都有这个内置的jQuery?没有这么幸运了:
首先,你的函数返回一个承诺:
function getData(id) {
return $.ajax({ // note the return
url: 'http://example.com/'+id,
dataType: 'jsonp',
success: function (d) {
console.log(d);
},
error: function() {
alert("ERROR")
}
});
}
现在,你把它们连在使用.then
调用一个循环。请注意,.then
只有在前一个承诺完成后才会执行。所以他们将一个接一个地依次运行。
var array = ['One', 'Two', 'Three'];
var p = $.when(1); // empty promise
array.forEach(function(el){
p = p.then(function(){
return getData(el);;
});
});
所有功能将依次运行。还剩下什么?返回值。当前的实现丢弃返回值。该解决方案使用for
var array = ['One', 'Two', 'Three'];
var p = $.when(1); // empty promise
var results = [];
array.forEach(function(el,index){
p = p.then(function(){
return getData(el);
}).then(function(data){
results[index] = data; // save the data
});
});
p.then(function(){
// all promises done, results contains the return values
});
为什么停在那里,虽然,让我们把它更好的:)你的整个代码可以缩短到
["One","Two","Three"].map(makeUrl).map($.get).reduce(function(prev,cur,idx){
return prev.then(cur).then(function(data){ results[idx] = data; });
},$.when(1)).then(function(){
// results contains all responses here, all requests are sync
});
function makeUrl(id){
return "http://example.com"+id+"?callback=?";
}
相关问题
- 1. 链jQuery承诺
- 2. 链接ajax请求与jQuery的承诺
- 3. javascript ES6动态链接承诺
- 4. ajax的承诺
- 5. 角承诺链自动化
- 6. 根据响应跳过一个承诺链中的jQuery承诺
- 7. ExpressJS /的NodeJS /承诺:从承诺链
- 8. 链接承诺内的承诺然后()
- 9. 如何破解多个Ajax承诺链?
- 10. angularJS链承诺
- 11. AngularJS承诺链
- 12. 承诺断链
- 13. 承诺链条
- 14. 承诺延期AJAX API jQuery的
- 15. jQuery的承诺则无法AJAX
- 16. 如何syncronize的链接jQuery的承诺
- 17. 角链的承诺
- 18. Q承诺 - 创建一个动态承诺链,然后触发它
- 19. jQuery中承诺的级联链转换
- 20. 如何解决jQuery中的承诺链?
- 21. 打破jQuery Ajax然后/承诺序列
- 22. 带有承诺的vue-i18n动态语言环境不更新
- 23. 使用带'require'的承诺来动态加载模块
- 24. 拒绝承诺链
- 25. Javascript承诺链 - ES6
- 26. 承诺分裂链
- 27. 延误承诺链
- 28. JavaScript承诺链接
- 29. 延迟承诺链
- 30. 链接ngResource承诺
你真的使用“缩短”这个词吗? –
是的,我相信我做到了。 –