Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

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的效果?


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

1 Answer

0 votes
by (71.8m points)

就算使用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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...