javascript中的异步foreach [英] Async foreach in javascript

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

问题描述

我希望这是有道理的: 我需要在javascript中创建一个foreach函数,将像这样使用:

I hope this will make sense: I need to create a foreach function in javascript that will be used like this:

foreach(["A", "B", "C"], function(letter, done) {
    // do something async with 'letter'
    doSomthing(letter, done); // ***
}, function () {
    // final callback that is called after all array has been visted.
    // do some final work
});

所以我正在考虑以下实现:

So I was thinking about the following implementation:

var foreach = function(array, func, ready) {
    if (!array.length)
        ready();
    var that = this;
    func(array[0], function(){
        that.foreach(array.slice(1, array.length), func, ready);
    });
}

似乎确实有效!很酷.

但是我在想是否有不使用递归的解决方案? 我想不到一个...

But I was thinking if there is a solution that doesn't use recursion? I couldn't think of one...

推荐答案

您的方法在技术上是正确的,但这样做并不好. 请在javasript中使用promise模式实现. 我建议您使用when.js在git上可用的开源js来实现承诺模式,请参考以下代码

Your approach is technically correct but it is not good to do in such a way. Pls implement using promise pattern in javasript . I recommend you using when.js an open source js available on git for implementing promise pattern Pls refert to the below code

   var service = {
            fetch: function (query) {

                // return a promise from the function
                return when(["A", "B", "C"].forEach(function (name) {
                    alert(name);
                }));
            }
        };

        service.fetch("hello world").then(function () {
            alert("work has been completed");
        });

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

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