The asynchronous function appears in the For loop of JS, the callback reference is always the last value of the loop value?

Source: Internet
Author: User

These days with video learning node. js, encountering a lot of problems with asynchronous functions, the problem of callback values for asynchronous functions appearing in a For loop is now summarized as follows:

The specific problem is the code that iterates over the subfolders in the folder for the For loop wrapping the Async function:

for (var i = 0; i < files.length; i++) {    var itemFile = files[i];    fs.stat("./uploads/" + itemFile, function (err, stats) {            if (stats.isDirectory()) {            console.log(itemFile+i);            } else {            console.log(2);        }    });}

The output is:

wedding3wedding3wedding3

The For loop is a synchronous task, and I continuously drops until equals file.length, and the loop no longer executes, which is equal to 3 (own experimental code). and the internal judgment of the loop is whether the Isdirectory function of the folder is an asynchronous function, that is, the internal console.log (itemfile+i); Execution is queued at the end of the task queue, so the for loop itself executes 3 times, but does not perform the task inside the callback, and the For loop ends when the Console.log in the callback function starts executing the first time, so each output is wedding3.

Of course, this is not the result we want, the solution can be done by self-executing function parameters (anonymous functions), so as to form a local scope not affected by external variables. Such as:

for (var i = 0; i < files.length; i++) {    (function(i){        var itemFile = files[i];        fs.stat("./uploads/" + itemFile, function (err, stats) {                if (stats.isDirectory()) {                console.log(itemFile+i);                } else {                console.log(2);            }        });    })(i);  }

The output gets:

cat0dog1wedding2

This solves the problem of outputting only the value of the last loop.

Front-end page development will also encounter similar problems, such as settimeout asynchronous execution of the problem, in the front end can be resolved through the jquery each solution. With jquery's $.each (), the function scope is formed by using the callback function.

<script type="text/javascript">    var arr = ["dog",cat","wedding"];    $.each(arr, function(key, value) {        setTimeout(function() {            console.log(key);            console.log(value);        }, 2000);    });</script>

The asynchronous function appears in the For loop of JS, the callback reference is always the last value of the loop value?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.