JavaScript

Promise

2018-07-25  本文已影响2人  YC____
参考文章http://blog.guowenfh.com/2018/06/04/2018/learning-Promise/

promise对象用于表示一个异步操作的最终状态,以及返回的值

链式回调,不用再写callback

request(1)
.then(data=>{
    console.log('promise',data)
    return request(2)
})
.then(data=>{
    console.log('promise',data)
    return request(3)
})
.then(data=>{
    console.log('promise',data)
})
.catch(data=>{
    console.log('error')
})
function request(e){
    return new Promise((resolve,reject)=>{
        setTimeout(()=>{
            switch (e) {
                case 1:
                    resolve('success1');
                    break;
                case 2:
                    resolve('success2');
                    break;
                case 3:
                    reject('success3');
                    break;
                default:
                    break;
            }
        },1000)
    })
}
//promise success1
//promise success2
//error

Promise对象上的方法

Promise.all()会将多个 Promise 实例封装成一个新的 Promise 实例,新的 promise 的状态取决于多个 Promise 实例的状态,只有在全体 Promise 都为 fulfilled 的情况下,新的实例才会变成 fulfilled 状态。;如果参数中 Promise 有一个失败(rejected),此实例回调失败(rejecte),失败原因的是第一个失败 Promise 的结果。

fetch('https://cnodejs.org/api/v1/topics?tab=good&limit=10')
.then(res=>res.json())
.then(res=>{
    const fecthList = res.data.map(t=>{
        return fetch(`https://cnodejs.org/api/v1/topic/${t.id}`)
        .then(res=>res.json())
        // .then(res=>res.data) //return res.data
    })
    Promise.all(fecthList).then(list=>{ //返回一个数组
        console.log(list)
    })
})

Promise.race Promise.race 也会将多个 Promise 实例封装成一个新的Promise实例,只不过新的 Promise 的状态取决于最先改变状态的 Promise 实例的状态。

fetch api模拟请求超时

Promise.race([
    fetch('https://cnodejs.org/api/v1/topics?tab=good&limit=10'),
    new Promise((resolve,reject)=>{
        setTimeout(reject,1000,'error')
    })
]).then(result=>{
    console.log('then',result)
}).catch(error=>{
    console.log('catch',error)
})

关于执行顺序

//在使用 Promise 构造函数构造 一个 Promise 时,回调函数中的内容就会立即执行,而 Promise.then 中的函数是异步执行的。
new Promise((resolve,reject)=>{
    console.log('step 1')
    resolve()
    console.log('step 2')
}).then(()=>{
    console.log('step 3')
})
console.log('step 4')
//step 1
//step 2
//step 4
//step 3
上一篇 下一篇

猜你喜欢

热点阅读