Async await strange behaviour with functions

前端 未结 2 2032
隐瞒了意图╮
隐瞒了意图╮ 2020-12-21 22:16

I have following asynchronous code example:

// Functions

function getSomePromise() {
    let a = new Promise((resolve, reject) => {    
        setTimeou         


        
2条回答
  •  梦毁少年i
    2020-12-21 22:49

    test2:

    your test2 is not async until you make it async. You've wrote synchronous code inside test2.they are the console.log. Only async code inside test2 is call to promise.Let's break it down

    async function test2() {
        for(let i=0; i<5; i++) {
            someWrapper(i);                
        }    
    }
    

    above code fires someWrapper() 5 times sequentially.so it write the first sync code which is console.log('A'+i) 5 times in a row in console.

    then each someWrapper() waits for async promise to return parallelly.after each promise resolved it prints 'Inside promise'. until the promise resolves, the execution halts and can not proceed to next step

    then, after resolving the promise, it prints out the second sync code which is console.log('B'+i) in console

    test1:

    test1 will behave differently than test2.Let's break it down

    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);
        }    
    }
    

    the main distinction is you are awaiting inside for loop. So this will literally pause the loop which was not the case for test1

    so for each iteration it will print console.log('A'+i)

    then pause the iteration for await getSomePromise()

    when the promise return will print 'Inside Promise'

    then print console.log('B'+i)

    then continue next iteration.

提交回复
热议问题