异步变同步

  1. promise.all
let behind = (time) => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            console.log( `${time}毫秒后` )
            resolve( `${time}毫秒后` )
        }, time)
    })
}

let p2 = behind(3000);
let p1 = behind(2000);
//两个以上ajax数据回来前显示loading
Promise.all([p2, p1]).then(res => {
    console.log('tag', res)
    // 2000毫秒后
    // 3000毫秒后
    // tag [ '3000毫秒后', '2000毫秒后' ]
}).catch(error => {
    console.log('tag', error)
})
  1. async await
function func1() {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve("func1 success")
        }, 1000)
    })
}

function func2() {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve("func2 success")
        }, 2000)
    })
}

let funcTest = async function() {
    try {
        let p2 = await func2();
        console.log(p2)
        let p1 = await func1();
        console.log(p1)
        //first. func2 success 
        //second func1 success
    } catch (error) {
        console.log(error)
    }

}
funcTest();

你可能感兴趣的:(es6)