Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
534 views
in Technique[技术] by (71.8m points)

javascript - Async await strange behaviour with functions

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Looking at the comments

@HMR - hm... I not understand - in question example there is async function someWrapper() but that function don't return anything (it even doesn't have return statement (!) ) - can you explain what do you mean by async functions immediately return a promise? - Kamil Kielczewski

it seems you don't understand the async await. I usually advice people to lay off await until you understand promises. However in next comment under question I give you the answer:

someWrapper will immediately return a promise that resolves to undefined. The await only "waits" in the someWrapper function but the function calling someWrapper will immediately receive a promise that resolves in undefined. Functions always return something, if you don't in code then it will return undefined. If it's an async function without a return then it'll return a promise that resolves in undefined - HMR.

Await is syntax sugar (nicer looking code) for promises and doesn't actually wait for anything.

Maybe the following code clears things up:

var test = async () => {
   await 22;//doesn't even matter if value is promise
   console.log("after wait");
}
var result = test();
console.log("outside test we don't wait for anything",result);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...