这是一个使用promise的好用例吗?

Is this a good use case for using Promises?

本文关键字:promise 一个      更新时间:2023-09-26

我正在处理一串xmlhttprequest,每个都依赖于它之前的一个。Psuedocode:

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();

在这种情况下,使用承诺将是一个好主意,以避免所有的回调垃圾?

是。如果你在一个then中返回一个promise,那么下一个链式会监听这个promise,而不是从原来的promise中解析。假设ajaxCall返回一个promise,那么您的代码将看起来像:

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

肯定是。假设有一个类似于如何保证原生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!');
});

当然仍然是回调,但不再需要嵌套。此外,您将有简单的错误处理,并且代码看起来更干净(部分原因是与承诺无关的事实,即在其自己的函数中抽象XHR)。