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

后端 未结 10 1645
时光说笑
时光说笑 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:27

    Edit 2018-10-11: It looks like there is a good chance the standard described below may not go through, consider pipelineing as an alternative (does not behave exactly the same but methods could be implemented in a similar manor).

    This is exactly why I am excited about es7, in future you will be able to do something like the code below (some of the specs are not complete so use with caution, I will try to keep this up to date). But basically using the new :: bind operator, you will be able to run a method on an object as if the object's prototype contains the method. eg [Object]::[Method] where normally you would call [Object].[ObjectsMethod]

    Note to do this today (24-July-16) and have it work in all browsers you will need to transpile your code for the following functionality:Import / Export, Arrow functions, Promises, Async / Await and most importantly function bind. The code below could be modfied to use only function bind if nessesary, all this functionality is neatly available today by using babel.

    YourCode.js (where 'lots of work to do' must simply return a promise, resolving it when the asynchronous work is done.)

    import { asyncForEach } from './ArrayExtensions.js';
    
    await [many many elements]::asyncForEach(() => lots of work to do);
    

    ArrayExtensions.js

    export function asyncForEach(callback)
    {
        return Promise.resolve(this).then(async (ar) =>
        {
            for(let i=0;i
        {
            const out = [];
            for(let i=0;i

提交回复
热议问题