循环承诺

时间:2015-07-22 22:17:41

标签: javascript asynchronous promise

我必须按顺序从服务器获取数据,我希望在Promises的帮助下完成。这是我到目前为止所尝试的:

LH <- which( test$"type" %in% c("low","high"))

for ( n in 1:(length(LH)-1) )
{
  dh1 <- as.numeric(test$"datehell"[LH[n]])
  dh2 <- as.numeric(test$"datehell"[LH[n+1]])

  m <- LH[n]

  while ( m < LH[n+1] )
  {
    dt <- (dh1*(LH[n+1]-m) + dh2*(m-LH[n])) / (LH[n+1]-LH[n])
    test$"datetime"[m] <- test$"datetime"[m] + as.difftime(dt,units="secs")
    m <- m+1                           
  }
}

test$"datetime"[LH[length(LH)]] <- test$"datetime"[LH[length(LH)]] + as.difftime(dh2,units="secs")

第一次获取成功,但后续对function getDataFromServer() { return new Promise(function(resolve, reject) { var result = []; (function fetchData(nextPageToken) { server.getData(nextPageToken).then(function(response) { result.push(response.data); if (response.nextPageToken) { fetchData(response.nextPageToken); } else { resolve(result); } }); })(null); }); } getDataFromServer().then(function(result) { console.log(result); }); 的调用未运行。我认为它与第一个server.getData()没有实现有关。我应该如何缓解这个问题?

2 个答案:

答案 0 :(得分:2)

因为then语句没有传递函数来处理错误情况,所以向服务器请求数据的数据可能会无提示失败,在这种情况下,getDataFromServer返回的promise将永远不会完成。

要解决此问题,请将第二个函数作为参数传递给then,如下所示:

function getDataFromServer() {
  return new Promise(function(resolve, reject) {
    var result = [];

    (function fetchData(nextPageToken) {

      server.getData(nextPageToken).then(function(response) {
        result.push(response.data);
        if (response.nextPageToken) {
          fetchData(response.nextPageToken);
        } else {
          resolve(result);
        }
      }).catch(function(error) {
        //Note: Calling console.log here just to make it easy to confirm this
        //was the problem.  You may wish to remove later.
        console.log("Error occurred while retrieving data from server: " + error);
        reject(error);
      });

    })(null);

  });
}

答案 1 :(得分:2)

Nimrand 回答了您的问题(缺少catch),但这是您的代码没有promise constructor antipattern

function getDataFromServer() {
  var result = [];

  function fetchData(nextPageToken) {
    return server.getData(nextPageToken).then(function(response) {
      result.push(response.data);
      if (response.nextPageToken) {
        return fetchData(response.nextPageToken);
      } else {
        return result;
      }
    });
  }
  return fetchData(null);
}

getDataFromServer().then(function(result) {
  console.log(result);
})
.catch(function(e) {
  console.error(e);
});

正如您所看到的,递归在承诺中效果很好。

&#13;
&#13;
var console = { log: function(msg) { div.innerHTML += "<p>"+ msg +"</p>"; }};

var responses = [
  { data: 1001, nextPageToken: 1 },
  { data: 1002, nextPageToken: 2 },
  { data: 1003, nextPageToken: 3 },
  { data: 1004, nextPageToken: 4 },
  { data: 1005, nextPageToken: 0 },
];

var server = {
  getData: function(token) {
    return new Promise(function(resolve) { resolve(responses[token]); });
  }
};

function getDataFromServer() {
  var result = [];

  function fetchData(nextPageToken) {
    return server.getData(nextPageToken).then(function(response) {
      result.push(response.data);
      if (response.nextPageToken) {
        return fetchData(response.nextPageToken);
      } else {
        return result;
      }
    });
  }
  return fetchData(0);
}

getDataFromServer().then(function(result) {
  console.log(result);
})
.catch(function(e) { console.log(e); });
&#13;
<div id="div"></div>
&#13;
&#13;
&#13;