xinggevip

Es2015 async、await
text.jsconst fs = require('fs'); const readFile = functi...
扫描右侧二维码阅读全文
18
2019/06

Es2015 async、await

text.js

const fs = require('fs');

const readFile = function (fileName){
    return new Promise((resolve,reject)=>{
        fs.readFile(fileName,(err,data) =>{
            if(err) reject(err);
            resolve(data);
        });
    });
};
// promise
readFile('data/a.txt').then((res)=>{
    console.log(res.toString());
    return readFile('data/b.txt');
}).then((res)=>{
    console.log(res.toString());
    return readFile('data/c.txt');
}).then((res)=>{
    console.log(res.toString());
})

// generator
function * gen(){
    yield readFile('data/a.txt');
    yield readFile('data/b.txt');
    yield readFile('data/c.txt');
};

let g1 = gen();
g1.next().value.then((res)=>{
    console.log(res.toString());
    return g1.next().value;
}).then((res)=>{
    console.log(res.toString());
    return g1.next().value;
}).then((res)=>{
    console.log(res.toString());
})

// async
async function fn(){

    let f1 = await readFile('data/a.txt');
    console.log(f1.toString());

    let f2 = await readFile('data/b.txt');
    console.log(f2.toString());

    let f3 = await readFile('data/c.txt');
    console.log(f3.toString());

};
fn();

// async特点:
// 1.await只能放到async函数中
// 2.星币generator语义化更强
// 3.await后面可以是promise对象,也可以是数字、字符串、布尔
// 4.async函数返回一个promise对象
// 5.只要await语句后面Promise状态变成reject,那么整个async函数会中断执行
//========================================================
//解决出错不执行问题
async function fgn(){
    // try{
    //     await Promise.reject("未知错误");
    // }catch(e){
    //     console.log(e)
    // };

    //这句通写法结果同上
    await Promise.reject("未知错误").catch((err)=>{
        console.log(err);
    });
    
    let a = await Promise.resolve("success");
    console.log(a);
};
fgn().then((res)=>{
    console.log(res);
}).catch((err)=>{
    console.log(err);
})

//promise.all配合async
async function sufn(){
    let [a,b,c] = await Promise.all([
        readFile('data/a.txt'),
        readFile('data/b.txt'),
        readFile('data/c.txt'),
    ]);
    console.log(a.toString());
    console.log(b.toString());
    console.log(c.toString());
};
sufn();

运行

node 文件路径
Last modification:June 18th, 2019 at 01:53 pm
If you think my article is useful to you, please feel free to appreciate

Leave a Comment