async-await如何在Javascript中工作? [英] How does async-await works in Javascript?

查看:74
本文介绍了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

这篇关于async-await如何在Javascript中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆