循环承诺 [英] Looping with Promises

查看:91
本文介绍了循环承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm in a scenario where I have to get data from the server in parts in sequence, and I would like to do that with the help of Promises. This is what I've tried so far:

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() 无法运行。我认为它与第一个然后()未实现有关。我应该如何缓解这个问题?

The first fetch is successful, but subsequent calls to server.getData() does not run. I presume that it has to do with that the first then() is not fulfilled. How should I mitigate this problem?

推荐答案

Nimrand 回答你的问题(缺少 catch ),但这里是没有承诺构造函数反模式的代码:

Nimrand answers your question (missing catch), but here is your code without the 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);
});

正如你所看到的,递归适用于承诺。

As you can see, recursion works great with promises.

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

<div id="div"></div>

这篇关于循环承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆