承诺使用Ajax请求进行循环 [英] Promise for-loop with Ajax requests

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

问题描述

我正在创建一个本机JavaScript应用程序,该应用程序在特定时间在同一过程中执行Ajax调用的加载.我认为我不会等待正常的for循环立即完成所有操作,而是等待Ajax调用完成,然后再执行下一个.

I'm creating a native JavaScript application which does loads of Ajax calls in the same process at a certain time. Instead of going through a normal for loop and do them all at once, I thought I'd wait for the Ajax call to complete and then do the next one.

在Stackoverflow的帮助下,我设法做到了以下内容:

With the help of Stackoverflow I've managed to do this like the following:

function ajaxCall(index) {
    return new Promise(function(resolve) {
        // Ajax request {
            resolve();
        // }
   });
}

Promise.resolve(0).then(function loop(i) {
    if (i < length) {
        return ajaxCall(i).thenReturn(i + 1).then(loop);
    }
}).then(function() {
    // for loop complete
});


Promise.prototype.thenReturn = function(value) {
    return this.then(function() {
        return value; 
    });
};

但是,这对我来说太慢了.我希望能够保留一个var来跟踪当前正在处理的Ajax调用数量,以便可以限制数量.

However, this is too slow for me. I want to be able to keep a var which keeps track of how many Ajax calls are currently in the process so that I can limit the amount.

我已经尝试了多种方法,但是我一直遇到ininite循环,或者没有达到期望的结果.

I've tried multiple things, but I keep running into ininite loops or not getting to the desired result.

如何使用Promise for循环执行多个(受特定数量限制的)异步Ajax调用?

How can I do multiple, limited by a specific number, async Ajax calls using the Promise for loop?

推荐答案

听起来像您想要的Promise.all版本,该版本需要一组异步函数而不是promise,并且要限制同时进行的操作数.像这样:

Sounds like you want a version of Promise.all that takes an array of asynchronous functions rather than promises, and a ceiling on the number of simultaneous operations. Something like:

Promise.allFuncs = (funcs, n) => {
  n = Math.min(n, funcs.length);
  var results = [];
  var doFunc = i => funcs[i]().then(result => {
    results[i] = result; // store result at the correct offset
    if (n < funcs.length) {
      return doFunc(n++);
    }
  });
  // start only n simultaneous chains
  return Promise.all(funcs.slice(0, n).map((p, i) => doFunc(i)))
    .then(() => results); // final result
};

// --- Example: ---

var log = msg => div.innerHTML += msg + "<br>";
var wait = ms => new Promise(resolve => setTimeout(resolve, ms));

var example = ['a','b','c','d','e','f'].map(name =>
  () => (log("started "+name),wait(2000).then(() => (log("ended "+ name), name))));
  
Promise.allFuncs(example, 2)
.then(results => log("Results: "+ results))
.catch(log);

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

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

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