promise 和 async await方法的用法实例(异步队列,执行有先后顺序)

// Promise用法和async await的区别
const takeLongTime = (n) => {
    return new Promise(resolve=>{
        setTimeout(() => {
            resolve(n+200)
        }, n);
    });
}
const step1=(n) =>{
    console.log(`step1 width ${n}`)
    return takeLongTime(n)
}
const step2=(m,n) =>{
    console.log(`step1 width ${m} and ${n}`)
    return takeLongTime(m+n)
}
const step3=(k,m,n) =>{
    console.log(`step1 width ${k} and ${m} and ${n}`)
    return takeLongTime(k+m+n)
}
// promise异步队列需要嵌套,需要异步的方法多了就非常繁琐
Promise.all([step1,step2,step3]).then(res=>{
    let arr = res;
    let t1=300;
    let time = [t1]
    arr[0](...time)
    .then(t=>{
        time.push(t)
        console.log(t)
        return arr[1](...time)
            .then(t=>{
                time.push(t)
                console.log(t)
                return arr[2](...time)
            })
    }).then(res=>{
        console.log(res,time)
        console.log(`result is ${res}`)
    })
})
// async await--从上到下阅读更清晰--es7--能够即刻得到结果
const queue3 = async () => {
    const time1= 300;
    const time2= await step1(time1)
    const time3= await step2(time1,time2)
    const result = await step3(time1,time2,time3)
    console.log(`result is ${time1},${time2},${time3},${result}`)
}
queue3();

promise还可以这么写:

Promise.all([step1,step2,step3]).then(res=>{
    let arr = res;
    let t1=300;
    let time = [t1]
    arr[0](...time)
    .then(t=>{
        time.push(t)
        console.log(t)
        return arr[1](...time)      
    })
    .then(t=>{
        time.push(t)
        console.log(t)
        return arr[2](...time)
    })
    .then(res=>{
        console.log(res,time)
        console.log(`result is ${res}`)
    })
})

 

promise

结果是:

step1 width 300
500
step1 width 300 and 500
1000
step1 width 300 and 500 and 1000
2000 [ 300, 500, 1000 ]
result is 2000

 

//***********************************************************************

await

结果是:

step1 width 300
step1 width 300 and 500
step1 width 300 and 500 and 1000
result is 300,500,1000,2000

 

 

我们可以通过promise模拟调用接口,通过输入方法的先后顺序执行得到我们想要的结果:

// 模拟接口--按我们输入的顺序执行--不管接口返回数据的快慢
let a=100
let b=200
let c=300
const getA = () => {
    return new Promise(function (resolve, reject) {
        setTimeout(function () {
            a = 1000
            resolve(Number(a));
        }, 4000);
    });
}

const getB = () => {
    return new Promise(function (resolve, reject) {
        setTimeout(function () {
            b=2000
            resolve(Number(b)+a);
        }, 2000);
    });
}
const getC = () => {
    return new Promise(function (resolve, reject) {
        setTimeout(function () {
            c=3000
            resolve(Number(c)+b+a);
        }, 1000);
    });
}

// 按照顺序依次获取结果
const dsth = (res) =>{
    console.log(res)
}
// 使用promise的all方法是并发的--没有明确先后顺序
Promise.all([getA(),getB(),getC()])
.then(res=>{
    console.log(...res)
    /*1000 2100 3300*/
})
//使用reduce封装promise
const queue1 = (things,fn) => {
    things.reduce((promise, thing) => {
        return promise.then(() => {
            return new Promise(resolve => {
                resolve(thing());
            })
            .then(res=>{
                if(fn && typeof (fn) === "function") fn(res)
            })
        });
    }, Promise.resolve());
}
console.log('case1')
queue1([getA,getB,getC],dsth)
/*
1000 3000 6000
*/

// foreach封装promise
const queue2 = (things,fn) => {
    let promise = Promise.resolve();
    things.forEach(thing => {
        promise = promise.then(() => {
            return new Promise(resolve => {
                resolve(thing());
            })
            .then(res=>{
                if(fn && typeof (fn) === "function") fn(res)
            })
        });
    });
    return promise;
}
console.log('case2')
queue2([getA,getB,getC],dsth)
/*
1000 3000 6000
*/


//使用aync await
const queue3 = async (things,fn) => {
    for(let thing of things) {
        if(fn && typeof (fn) === "function") fn(await thing())
    }
}
console.log('case3')
queue3([getA,getB,getC],dsth)
/*
1000 3000 6000
*/

// async await =>es7新增运算符,新的语言元素,有如下特点:

// 1.赋予JavaScript以顺序手法编写异步脚本的能力

// 2.既保留异步运算的无阻塞特性,还继续使用同步写法

// 3.还能正常使用return/try/catch


 

// 为啥还要学Promise?

// async await仍然需要Promise

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值