I have following asynchronous code example:
// Functions
function getSomePromise() {
let a = new Promise((resolve, reject) => {
setTimeout(function(){
console.log("Inside promise...");
resolve("Success!");
}, 1000);
});
return a;
}
async function someWrapper(i) {
console.log('A: '+ i);
await getSomePromise();
console.log('B: ' + i);
}
And two tests:
async function test1() {
for(let i=0; i<5; i++) {
// body copy-pasted of someWrapper function:
console.log('A: '+ i);
await getSomePromise();
console.log('B: ' + i);
}
}
async function test2() {
for(let i=0; i<5; i++) {
someWrapper(i);
}
}
And here are results in chrome console after run separatley test1()
and test2()
:
Test 1 | Test 2
---------------------------------------------
A: 0 | A: 0
Inside promise... | A: 1
B: 0 | A: 2
A: 1 | A: 3
Inside promise... | A: 4
B: 1 | Inside promise...
A: 2 | B: 0
Inside promise... | Inside promise...
B: 2 | B: 1
A: 3 | Inside promise...
Inside promise... | B: 2
B: 3 | Inside promise...
A: 4 | B: 3
Inside promise... | Inside promise...
B: 4 | B: 4
Question: Why when we use function someWrapper()
in for-loop
(test2) we get different result than wen we copy-paste this function body directly into for-loop
(test1) ?
(above example is quite abstract, however "I found this behaviour" on calling ajax requests (instead console.log('A: '+ i);
and console.log('B: '+ i);
) which sequence are very important in my app (request A1
must be before request B0
...) )
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…