我正在使用一串XMLHttpRequests,每个XMLHttpRequests都依赖于它之前的那个。伪码:
xhr1.open('GET', 'http://foo.com');
xhr1.onload = function(e){
xhr2.open('POST', xhr1.response.url)
xhr2.onload = function(e){
xhr3.open('GET', xhr2.response.url2);
xhr3.onload = function(e){
console.log('hooray! you have data from the 3rd URL!');
}
xhr3.send();
}
xhr2.send();
}
xhr1.send();
在这种情况下,使用promises是一个好主意,以避免所有的回调淤泥?
答案 0 :(得分:2)
是。如果您在then
中返回一个承诺,则下一个链接会侦听该承诺,而不是从原始承诺中解析。鉴于ajaxCall
返回一个承诺,您的代码将如下所示:
ajaxCall(1)
.then(function(result1){
return ajaxCall(2);
})
.then(function(result2){
return ajaxCall(3);
})
.then(function(result3){
// all done
});
// Sample AJAX call
function ajaxCall(){
return new Promise(function(resolve, reject){
// xhr code. call resolve/reject with accordingly
// args passed into resolve/reject will be passed as result in then
});
}
答案 1 :(得分:1)
是的,确切地说。假设辅助函数类似于How do I promisify native XHR?的函数,您的代码可以转换为
makeRequest('GET', 'http://foo.com').then(function(response1) {
return makeRequest('POST', response1.url);
}).then(function(response2) {
return makeRequest('GET', response2.url2);
}).then(function(response3) {
console.log('hooray! you have data from the 3rd URL!');
});
仍为callbacks of course,但no more nesting required。此外,您还可以进行简单的错误处理,并且代码看起来更清晰(部分是由于在其自身功能中抽象XHR的非承诺相关事实)。