Loop call asynchronous operation

Recently, I met an interesting interview question. The question is very simple, but it involves a lot of small knowledge points. It's quite interesting.

An ordinary for loop outputs i

// Normally write a for loop and output i
for (var i = 0; i < 5; i++) {
    console.log(i);
}
console.log(i);

Suppose you are an interviewer, what will these lines of code output?, Will your inner activity be "isn't this a cycle? Since the interviewer asks me so (he still smiles, it must be a bad thing, there must be a trap), think about it. It seems to be very similar to the closure question I read. Isn't the interviewer finished? What should I do?"

If you change a little, what is the output result?

There is a timer in the for loop

for (var i = 0; i < 5; i++) {
    setTimeout(function () {
        console.log(new Date, i);
    }, 1000 * i);
}
console.log(new Date, i);

After adding a little bit of information (setTimeout), is it comfortable to see this problem, and will you think, "'isn't this the closure problem i recite the most? Think about it. SetTimeout will delay the execution, so the external log will execute first. i is declared with var, so it will increase the variable. In the for loop, i finally executes i + +, and i becomes 5. That's right, i scored on this problem." .

Closure resolution.

// closure
for (var i = 0; i < 5; i++) {
    ~function (j) {
        setTimeout(function () {
            console.log(new Date, j);
        }, 1000 * j);
    }(i);
}

Follow the previous program and think, "can I sublimate it and run 0 1 2 3 4?"

Implement

var roles = ['Role 1', 'Role 2', 'Role 3'];
var arrayTest = [];
for (var i = 0; i < roles.length; i++) {
    !function (i) {
        $.get('https://www.baidu.com', { role: roles[i] }, function (res) {
            console.log(i);
            arrayTest[i] = i + roles[i] + res;
        })
    }(i);
}

If you log in to a background system and there are different roles under this account (roles are not fixed and may be added later), you can send different roles to make ajax requests to get the data of the corresponding rendered page, but this interface only receives one role parameter, how can we get the data in the order we want and then render the page?

es6

const tasks = [];
for (var i = 0; i < 5; i++) {
    ((j) => {
        tasks.push(new Promise((resolve) => {
            setTimeout(() => {
                console.log(new Date, j);
                resolve();
            }, 1000 * j); // The timeout of the timer increases gradually
        }));
    })(i);
}
 
Promise.all(tasks).then(() => {
    setTimeout(() => {
        console.log(new Date, i);
    }, 1000);
});

When you have successfully answered all the questions in front of you, have you ever thought that 20% of people may be able to answer to your level, how can you realize a little better than them? You can consider using promise

setTimeout and promise priority

setTimeout(function () {
    console.log(1)
}, 0);
new Promise(function executor(resolve) {
    console.log(2);
    for (var i = 0; i < 10000; i++) {
      i == 9999 && resolve();
    }
    console.log(3);
}).then(function () {
    console.log(4);
});
console.log(5);

"This question should examine the operating mechanism of JavaScript. Let me sort it out.

First, a setTimeout is encountered, so a timing will be set first. After the timing is over, the function will be passed to the task queue, so 1 will not be output at the beginning.

Then there is a Promise. The functions in it are executed directly, so they should output 2 and 3 directly.

Then, Promise's then should be placed at the end of the current tick, but still in the current tick.

Therefore, 5 should be output first and then 4.

Finally, the next tick is 1.

2 3 5 4 1"

es7

const sleep = (timeountMS) => new Promise((resolve) => {
    setTimeout(resolve, timeountMS);
});
 
(async () => { // async function expression that is declared and executed
    for (var i = 0; i < 5; i++) {
        await sleep(1000);
        console.log(new Date, i);
    }
 
    await sleep(1000);
    console.log(new Date, i);
})();

If you want to give the interviewer a better impression of focusing on new technology, use es7

Keywords: Javascript ECMAScript Interview

Added by pikemsu28 on Tue, 12 Oct 2021 06:39:26 +0300