在解决之前,承诺会被提前多次拒绝

时间:2016-11-18 18:38:56

标签: javascript es6-promise

我正在调用API,然后尝试渲染返回数据的图表:

(eval-after-load 'ox-latex (add-to-list 'org-export-latex-classes ...))

当我加载该脚本时,我在控制台中获得function getFromAPI(url) { return new Promise( (resolve, reject) => { let xhr = new XMLHttpRequest(); xhr.onreadystatechange = () => { if (xhr.readyState == 4 && xhr.status == 200) { console.log("Resolving!"); jsonData = JSON.parse(xhr.responseText); resolve(jsonData); } else { console.log("Rejecting!"); reject(); } } xhr.open("GET", url, true); xhr.send(); }); } getFromAPI(API_URL).then( (jsonData) => { drawChart(jsonData) }); 三次才会结算。 Rejecting!也打破reject部分(即我没有图表!)

我认为.then事件在我们到达onreadstatechangereadyState == 4之前触发了几次。到底发生了什么,我如何避免过早拒绝承诺呢?

1 个答案:

答案 0 :(得分:4)

onreadystatechange是一个事件处理程序,只要xhr readyState发生变化就会触发。

0   UNSENT  Client has been created. open() not called yet.
1   OPENED  open() has been called.
2   HEADERS_RECEIVED    send() has been called, and headers and status are available.
3   LOADING Downloading; responseText holds partial data.
4   DONE    The operation is complete.

正如你所看到的那样有4"没有准备好"国家,一个"完成"。这说明了您看到的拒绝和解析的控制台日志。

当请求完成"完成"时,根据状态拒绝或解决请求:

xhr.onreadystatechange = () => {
  if (xhr.readyState !== 4) {
    return;
  }

  if (xhr.status === 200) {
    console.log("Resolving!");
    jsonData = JSON.parse(xhr.responseText);
    resolve(jsonData);
    return;
  }

  console.log("Rejecting!");
  reject();
}