如何在循环中生成异步请求?

时间:2016-11-03 18:37:10

标签: javascript node.js recursion promise cycle

var userName = 'realgrumpycat';
var moreAvailable = true;
var lastId = '';

while (moreAvailable)
{
    getPhotosDataFromRequest(userName, lastId).then(function (data)
    {
        moreAvailable = data.more_available;
        lastId = data[data.length - 1].id;
        console.log(data);
    });
}

getPhotosDataFromRequest()返回带有数据的新Promise()和JSON。我想在 cyscle 多次执行此方法。但是正如我在调试器中看到的那样,while循环执行得如此之快,以至于没有进入承诺然后阻止

2 个答案:

答案 0 :(得分:1)

尝试使用函数递归:

var userName = 'realgrumpycat';
var lastId = '';

var getPhotos = function()
{
    getPhotosDataFromRequest(userName, lastId).then(function (data)
    {
        lastId = data[data.length - 1].id;
        console.log(data);

        if (data.more_available) 
        {
            getPhotos();
        }
    });
};

getPhotos();

答案 1 :(得分:0)

正如迭代替代(作为概念),但在现实生活中不是真正的解决方案,因为性能和限制:

//i try to use here es5 only
var userName = 'realgrumpycat';
var moreAvailable = true;//<-- can be removed
var lastId = ''; //<-- can be removed
var maxRequests = 1000; //e.g. max 1000 requests

//create empty promise to resolve later
var resolveStart = null;
var request = new Promise(function(resolve){
  resolveStart = resolve;
});

//append 1000 potential requests
for(var i = 0; i < maxRequests; i++) {
  request = request.then(createRequestPromise);
}

//here you probably should differ the "done" rejection and other errors
request.catch(function(){});

//now resolve the first promise, with empty string, to start the request chain
resolveStart('');

function createRequestPromise(lastId) {
    return getPhotosDataFromRequest(userName, lastId).then(function (data)
    {
        lastId = data[data.length - 1].id;
        console.log(data);
        //stop the chain by rejection
        if (!data.more_available) return Promise.reject('done');

        return lastId;
    });
}