相关疑难解决方法(0)

使用ES6的Promise.all()时限制并发性的最佳方法是什么?

我有一些代码在一个列表中进行迭代,该列表从数据库中查询并为该列表中的每个元素发出HTTP请求.该列表有时可能是一个相当大的数字(成千上万),我想确保我没有遇到数千个并发HTTP请求的Web服务器.

此代码的缩写版本目前看起来像这样......

function getCounts() {
  return users.map(user => {
    return new Promise(resolve => {
      remoteServer.getCount(user) // makes an HTTP request
      .then(() => {
        /* snip */
        resolve();
      });
    });
  });
}

Promise.all(getCounts()).then(() => { /* snip */});
Run Code Online (Sandbox Code Playgroud)

此代码在Node 4.3.2上运行.重申Promise.all一下,可以进行管理,以便在任何给定时间只有一定数量的Promise正在进行中?

javascript node.js es6-promise

67
推荐指数
7
解决办法
3万
查看次数

多个,顺序fetch()承诺

我必须制作一系列fetch()Promise:我一次只有1个url,这意味着只有1个fetch()promise.每次我收到一个json,这个包含另一个json的url,所以我必须做出另一个fetch()承诺.

我可以使用多个承诺,但在这种情况下我不能这样做Promise.all(),因为我没有所有网址,只有一个网址.

这个例子不起作用,它都冻结了.

function fetchNextJson(json_url) 
{
    return fetch(json_url, {
            method: 'get'
        })
        .then(function(response) {
            return response.json();
        })
        .then(function(json) {
            console.log(json);
            return json;
        })
        .catch(function(err) {
            console.log('error: ' + error);
        });
}


function getItems(next_json_url) 
{
    if (!(next_json_url)) return;

    get_items = fetchNextJson(next_json_url);

    interval = $q.when(get_items).then(function(response) {
        console.log(response);
        next_json_url = response.Pagination.NextPage.Href;
    });

    getItems(next_json_url);
}


var next_json_url = 'http://localhost:3000/one';

getItems(next_json_url);
Run Code Online (Sandbox Code Playgroud)

javascript json promise angularjs es6-promise

3
推荐指数
1
解决办法
3063
查看次数

标签 统计

es6-promise ×2

javascript ×2

angularjs ×1

json ×1

node.js ×1

promise ×1