(重点理解)彻底弄懂怎么正确使用async/await

2019-11-11  本文已影响0人  糖醋里脊120625

彻底弄懂怎么正确使用async/await

//微任务
const p1 = () => new Promise((resolve, reject) => {
    resolve('微任务')
}).then(res => {
    console.log(res)
})
//宏任务
const p2 = () => new Promise(res => setTimeout(() => {
    res('宏任务')
},1000)).then(res => {
    console.log(res)
})
const add = async () => {
    console.log(1)
    await p2()
    await p1()
    console.log(4)
}
add()

简化成函数
const pipeAsync = (...args) => arg => args.reduce((acc, val) => {
    return acc.then(val)
}, Promise.resolve(arg))

const sum = pipeAsync(
    x => x + 1,
    x => new Promise(resolve => setTimeout(() => {
        resolve(x * 4)
    }, 1000)),
    x => new Promise(res => res(x * 10)),
    x=>x+10

);
(
    async () => {
        //5+1   *4  *10  +10
        console.log(await sum(5))
    }
)()
const arrayFromRange = function arrayFromRange(min, max) {
    const output = []
    for (let i = min; i <= max; i++)
        output.push(i)
    return output
}
console.log(arrayFromRange(1, 10))
//[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
//优化后
const arrayFrom = (min, max) =>
    Array.from({length: max - min+1}, (_, i) => i + min)
console.log(arrayFrom(1, 10))
//[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
上一篇 下一篇

猜你喜欢

热点阅读