Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - Does all async function code will run i a different thread?

I have wrote the following code:

async function imaAsyncFunction () {
    console.log('1234');
    let res = await setTimeout(()=>{console.log('10 sec');},10000);
    console.log(res);
    console.log('is After?!?');
}

imaAsyncFunction();
console.log('bla bla bla');

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

1 Answer

0 votes
by (71.8m points)

Does all async function code will run i a different thread?

No. async functions, await, and promises do not create or use different threads.

A promise doesn't make anything asynchronous on its own1, it's just a way of observing the completion of something that's already asynchronous (like your timer callback, which uses the timer subsystem of your environment to call your timer callback later).

async functions are "just" a way (a really, really useful way) to wait for promises to settle via syntax rather than by attaching fulfillment and rejection handlers using the .then or .catch methods.

I was a little surprise that the line console.log(res); was printed before the 10 seconds of timeout was finished, but i guess that the reason is that the code after await doesn't return a Promise.

setTimeout doesn't return a promise, right. So await doesn't wait for the timer callback to occur. See this question's answers for how you'd make a promise-enabled version of setTimeout.

But, why does the code : console.log('bla bla bla'); was printed before both lines:

For the same reason: Your async function returns a promise, and your code calling your async function doesn't wait for that promise to be settled before moving on to the console.log('bla bla bla') line.

Here's code that both uses a promise-enabled version of setTimeout and waits for your async function's promise to settle before doing the console.log:

function delay(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}
async function imaAsyncFunction () {
    let res = await delay(800); // 0.8s instead of 10s
    console.log("Timer expired");
    console.log(res); // undefined, since we haven't set a fulfillment value
    console.log("is after");
}

imaAsyncFunction()
.then(() => {
    console.log("bla bla bla");
})
.catch(error => {
    console.error(error);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...