async await是如何做到异步阻塞的?

await有一个最让我不能理解的点就是怎么能做到阻塞异步的同时也将其下的同步语句阻塞。
都知道yield+promise能做到异步阻塞,但我写不出将后面的同步语句也阻塞的方法。
我的写法实现如下:

function mission(){
    return new Promise(resolve=>{
        setTimeout(()=>{
            resolve(123);
        },1000);
    });
}

function *test(){
    const res=yield mission();
    console.log(res);
}

function handler(gen,data){
    const {value,done}=gen.next(data);
    if(!done){
        if(value instanceof Promise){
            value.then(res=>handler(gen,res));
        }else{
            handler(gen);
        }
    }else{
        gen.next(value);
    }
}

function fn(){
    handler(test());
//这里无法被阻塞!
    console.log(321);
//打印结果为:
//  321
//  123
}

fn();

但是当我改写成async的写法时却能做到阻塞。

//改写fn函数
async function fn(){
    await mission();
    console.log(321);
}
fn();
//打印结果为:
//  123
//  321

所以我想请问一下各位大佬,如果用yield+promise写出async的效果?

阅读 4.2k
1 个回答

就算使用async也不能方法外面同步呀,只能保证方法里面同步,加了async这个方法就是异步了

你的两个对比写法完全不一样呀,没法对比

下面是对比:

正确写法:

// yield
function *test(){
    const res=yield mission();
    console.log(res);
    console.log('321')
}

handler(test());
// 123
// 321

// async
async function fn(){
    const res = await mission();
    console.log(res)
    console.log(321);
}
fn();
// 123
// 321

写在外面:

// yield
function *test(){
    const res=yield mission();
    console.log(res);
}

handler(test());
console.log('321')
// 321
// 123

// async
async function fn(){
    const res = await mission();
    console.log(res)
}
fn();
console.log(321);
// 321
// 123
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题