这是使用 Promises 的好用例吗?
Is this a good use case for using Promises?
我正在处理一串 XMLHttpRequest,每个都依赖于它之前的那个。伪代码:
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 是避免所有回调混乱的好主意吗?
是的。如果你 return 一个 then
中的承诺,那么下一个链式会监听那个承诺,而不是从原来的承诺中解析。鉴于 ajaxCall
return 是一个承诺,您的代码将如下所示:
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
});
}
是的,绝对是。假设像 中的辅助函数,您的代码可以转换为
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, but no more nesting required。此外,您还可以进行简单的错误处理,并且代码看起来更清晰(部分原因是在其自身函数中抽象 XHR 的非承诺相关事实)。
我正在处理一串 XMLHttpRequest,每个都依赖于它之前的那个。伪代码:
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 是避免所有回调混乱的好主意吗?
是的。如果你 return 一个 then
中的承诺,那么下一个链式会监听那个承诺,而不是从原来的承诺中解析。鉴于 ajaxCall
return 是一个承诺,您的代码将如下所示:
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
});
}
是的,绝对是。假设像
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, but no more nesting required。此外,您还可以进行简单的错误处理,并且代码看起来更清晰(部分原因是在其自身函数中抽象 XHR 的非承诺相关事实)。