JavaScript, Node.js: is Array.forEach asynchronous?

后端 未结 10 1587
时光说笑
时光说笑 2020-11-22 10:47

I have a question regarding the native Array.forEach implementation of JavaScript: Does it behave asynchronously? For example, if I call:

[many          


        
10条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 11:53

    It is possible to code even the solution like this for example :

     var loop = function(i, data, callback) {
        if (i < data.length) {
            //TODO("SELECT * FROM stackoverflowUsers;", function(res) {
                //data[i].meta = res;
                console.log(i, data[i].title);
                return loop(i+1, data, errors, callback);
            //});
        } else {
           return callback(data);
        }
    };
    
    loop(0, [{"title": "hello"}, {"title": "world"}], function(data) {
        console.log("DONE\n"+data);
    });
    

    On the other hand, it is much slower than a "for".

    Otherwise, the excellent Async library can do this: https://caolan.github.io/async/docs.html#each

提交回复
热议问题