在JavaScript中循环异步 [英] Asynchronous for cycle in JavaScript

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

问题描述

我需要一个等待异步调用的循环才能继续。类似于:

I need a loop that waits for an async call before continuing. Something like:

for ( /* ... */ ) {

  someFunction(param1, praram2, function(result) {

    // Okay, for cycle could continue

  })

}

alert("For cycle ended");

我怎么能这样做?你有任何想法吗?

How could I do this? Do you have any ideas?

推荐答案

如果阻止脚本,你不能在JavaScript中混合同步和异步,你阻止了浏览器。

You can't mix synchronous and asynchronous in JavaScript if you block the script, you block the Browser.

你需要在这里采用完整的事件驱动方式,幸运的是我们可以隐藏丑陋的东西。

You need to go the full event driven way here, luckily we can hide the ugly stuff away.

编辑:更新了代码。

function asyncLoop(iterations, func, callback) {
    var index = 0;
    var done = false;
    var loop = {
        next: function() {
            if (done) {
                return;
            }

            if (index < iterations) {
                index++;
                func(loop);

            } else {
                done = true;
                callback();
            }
        },

        iteration: function() {
            return index - 1;
        },

        break: function() {
            done = true;
            callback();
        }
    };
    loop.next();
    return loop;
}

这将为我们提供一个异步循环,你当然可以进一步修改它以获取一个函数来检查循环条件等。

This will provide us an asynchronous loop, you can of course modify it even further to take for example a function to check the loop condition etc.

现在进行测试:

function someFunction(a, b, callback) {
    console.log('Hey doing some stuff!');
    callback();
}

asyncLoop(10, function(loop) {
    someFunction(1, 2, function(result) {

        // log the iteration
        console.log(loop.iteration());

        // Okay, for cycle could continue
        loop.next();
    })},
    function(){console.log('cycle ended')}
);

输出:

Hey doing some stuff!
0
Hey doing some stuff!
1
Hey doing some stuff!
2
Hey doing some stuff!
3
Hey doing some stuff!
4
Hey doing some stuff!
5
Hey doing some stuff!
6
Hey doing some stuff!
7
Hey doing some stuff!
8
Hey doing some stuff!
9
cycle ended

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

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