天下无坑

天下无坑


Promise、async、await

声明一个Promise对象

// 常规写法
var p = new Promise(function(resolveFn, rejectFn){
    //做一些异步操作
    setTimeout(function(){
        console.log('执行完成');
        resolveFn('随便什么数据');
    }, 2000);
});

// 箭头函数
var p = new Promise((resolveFn, rejectFn)=>{
    //做一些异步操作
    setTimeout(function(){
        console.log('执行完成');
        resolveFn('随便什么数据');
    }, 2000);
});

// 箭头函数,省略rejectFn
var p = new Promise(resolveFn=>{
    //做一些异步操作
    setTimeout(function(){
        console.log('执行完成');
        resolveFn('随便什么数据');
    }, 2000);
});

多个异步的顺序执行写法

function takeLongTime(n) {
    // 返回一个Promise对象
    return new Promise(resolve => {
        setTimeout(() => resolve(n + 200), n);
    });
}

async function doIt() {
    //time1 阻塞等待一个Promise对象的完成,并接收到resolve的值
    const time1 = await takeLongTime(100);
    console.log(`time1 is ${time1}`);

    const time2 = await takeLongTime(200);
    console.log(`time2 is ${time2}`);

    const time3 = await takeLongTime(300);
    console.log(`time3 is ${time3}`);

    return 'done'
}
doIt().then(returnValue => {
    console.log(returnValue) //done
}).catch(error => {
  console.log(error)
})

多个异步的并列执行写法

let wake = (time) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(`${time / 1000}秒后醒来`)
    }, time)
  })
}

let p1 = wake(3000)
let p2 = wake(2000)

Promise.all([p1, p2]).then((result) => {
  console.log(result)       // [ '3秒后醒来', '2秒后醒来' ]
}).catch((error) => {
  console.log(error)
})
  • then()

  • catch()

  • all()

  • race()

页面列表

ITEM_HTML