async-await如何在Javascript中工作?

async-await如何在Javascript中工作?

问题描述:

使函数异步会使它异步吗?

Does making a function async make it asynchronous?

我开始使用async-await代替Promise链.我做了类似的事情

I started using async-await in place of promise chain. I did something like

async function f(){
    let r = await first();
    let d = await sec(r);
    return d;
}

在调用此函数时,我能够看到所有代码都是异步发生的.但是在一些较老的文章中,我读到我们无法在javascript中创建异步函数.使功能异步也会使其异步.

On calling this function I was able to see that all code happened asynchronously. But in some older article I read we can't create asynchronous function in javascript. So does making function async makes it asynchronous.

使函数异步会使它异步吗?

Does making a function async make it asynchronous?

不,不是.

是的,我们无法在javascript中创建异步函数.我们可以在执行异步任务后使用异步函数执行代码,但是代码只能在我们的单线程中执行.

Yes, we can not create asynchronous function in javascript. We can use asynchronous function to execute our code after a asynchronous task but code will be executed in our single thread only.

await 在async-await中是异步的,当编译器到达await时,它将停止执行并将所有内容推送到事件队列中,并在async函数之后继续执行同步代码.例子

await is asynchronous in async-await, when compiler reach at await it stops executing and push everything into event queue and continue with synchronous code after async function. Example

function first() {
    return new Promise( resolve => {
        console.log(2);
        resolve(3);
        console.log(4);
    });
}

async function f(){
    console.log(1);
    let r = await first();
    console.log(r);
}

console.log('a');
f();
console.log('b');

由于等待是异步的,因此等待之前的所有其他事情都照常发生

Since await is asynchronous thus every other thing before await happens as usual

a
1
2
4
b
// asynchronous happens
3