简体   繁体   中英

await not doing what I expect

async function doThings() {
    async function timer () {
        setTimeout(() => {
            console.log('timer!')
        }), 1000
    }
    
    async function printer () {
        console.log('printer!')
    }

    await timer()
    await printer()
}

doThings()

I thought making the function async made it return a promise and await made it wait. Why does printer() finish first?

Your timer function doesn't work because setTimeout does not return a promise that could be awaited. You will need to promisify it manually:

// set a default of 1500
function timeout(ms=1500) {
  return new Promise(resolve => setTimeout(resolve, ms));
};

async function printer() {
  console.log('printer!');
};

async function doThings() {
  await timeout(1000); // time in ms
  await printer();
};

doThings();

我只能看到 timer () 和 printer () 函数是异步函数,但是它们中没有使用 await,这使得 async 关键字不起作用。

The word “async” before a function means one simple thing: a function always returns a Promise. Other values are wrapped in a resolved Promise automatically.

Now when we use don't return Promise from async function, then javascript interpreter automatically returns resolved Promise, so that is the reason await on timer function got the resolved Promise and interpreter went ahead with the execution, but there is a setTimeout still going on. So we have to return a Promise from timer function, and resolve it inside setTimeout function like below.

async function doThings() {

    async function timer() {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                console.log(`timer!`);
                resolve();
            }, 1000)
        });
    }

    async function printer() {
        console.log('printer!')
    }

    await timer()
    await printer()
}

doThings()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM