Promise对象

一、Promise 有三个状态

  1、pending(进行中)

  2、fulfilled(已成功)

  3、rejected(已失败)

 

案例1

function  delayFn () {
    return new Promise((resolve, reject) => {
        setTimeout (() => {
            resolve()
        },3000)
    })
}
delayFn().then(() => {
    console.log('dfdfdf')
}).catch(err => {
    console.log(err)
})
View Code

 案例2 (Promise.all() 并发执行

function fn1 () {
    return new Promise((resolve, reject) =>{
        resolve('one')
    }).catch(err => {
        throw new Error(err)
    })
}
function fn2 () {
    return new Promise((resolve, reject) =>{
        resolve('two')
    }).catch(err => {
        throw new Error(err)
    })
}
let res = Promise.all([fn1(), fn2()])
res.then(v =>{
    console.log(v)
})
View Code

案例3 (异步超时,取消用Promise.race()

function fn1() {
    return new Promise((resolve, reject) => {
        setTimeout(function() {
            resolve('finish')
        }, 3000);
    });
}
function cancel() {
    return new Promise((resolve, reject) => {
        setTimeout(function() {
            resolve('超时了')
        }, 1000);
    });
}
let promise = Promise.race([fn1(), cancel()])
promise.then((value) => {
        console.log(value) // -> 超时了
})
View Code

 

posted @ 2017-09-22 14:50  浮生如梦似离殇  阅读(140)  评论(0编辑  收藏  举报