承诺使用Ajax请求进行循环

编程入门 行业动态 更新时间:2024-10-26 04:22:59
本文介绍了承诺使用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请求进行循环

本文发布于:2023-10-10 01:22:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1477298.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Ajax

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!