2018-01-02 async 函数要点

async 函数

async 返回的是promise, await 后面应该是个promise,否则立即resolve

try catch 防止rejected

async function myFunction() {
try {
    await somethingThatReturnsAPromise();
} catch (err) {
    console.log(err);
}
}
// 另一种写法
async function myFunction() {
    await somethingThatReturnsAPromise()
    .catch(function (err) {
        console.log(err);
    };
}

并发与继发

async function asyncPrint(value,ms){
    let a = new Promise((resolve)=>{setTimeout(resolve,ms)});
    let b = new Promise((resolve)=>{setTimeout(resolve,ms)});
    await a;console.log(value+1111)
    await b;console.log(value+22222)

}
asyncPrint('dddd',3000)//并发执行
-----------------------------------------
async function asyncPrint(value,ms){
    await new Promise((resolve)=>{setTimeout(resolve,ms)});
    console.log(value+1111)
    await new Promise((resolve)=>{setTimeout(resolve,ms)});
    console.log(value+22222)

}
asyncPrint('dddd',3000)//继发执行
------------------------------------
function P(){
    return new Promise((resolve)=>{setTimeout(()=>resolve('dddd'),2000)})
}
let docs = [P(),P(),P()]
async function bingfa1(db){
    let result = await Promise.all(docs);
    console.log(result)
}
//Promise.all 并发执行 
------------------------------------
async function jifa(db){
    let result = [];
    for(var i of [0,1,2]){
        let val = await P();
        result.push(val)
    }
    console.log(result)
}
jifa()
//for of 继发执行推荐
------------------------------------
async function bingfa2(db){
    let result = [];
    docs.forEach(async function(){
        let a = await P();
        result.push(a)
        console.log(result)
    })
    console.log(result)
}
bingfa2()
//forEach 并发执行(不推荐)

你可能感兴趣的:(2018-01-02 async 函数要点)