使用
var p = new Promise(function(resolve, reject){
console.log('执行')
setTimeout(function(){
resolve(2)
}, 1000)
})
p.then(function(res){
console.log('suc',res)
},function(err){
console.log('err',err)
})
手写 Promise
function Promise(executor) {
var _this = this;
this.status = 'pending'; // 状态
this.value = undefined; // 成功结果
this.reason = undefined; // 失败原因
function resolve(value){ this.state = 'fullfilled' }
function reject(reason){ this.state = 'rejected' }
executor(resolve, reject);
}
Promise.prototype.then = function(onFullfilled, onRejected){
if(this.state === 'fullfilled'){
onFullfilled(this.value)
}
if(this.state === 'rejected'){
onRejected(this.reason)
}
}
module.exports = Promise;
promise.all
Promise.all = (promises) => {
return new Promise((rs, rj) => {
let count = 0;
let len = promises.length;
let result = [];
if(len === 0) return rs([])
promises.forEach((item, index) => {
Promise.resolve(p).then(res => {
count +=1;
result[i] = res;
if(count === len) return rs([])
})
}).catch(rj)
})
}
取消Promise方法
- 当新对象保持“pending”状态时,原Promise链将会中止执行。 ```javascript Promise.resolve().then(() => { console.log(‘ok1’) return new Promise(()=>{}) // 返回“pending”状态的Promise对象 }).then(() => { // 后续的函数不会被调用 console.log(‘ok2’) }).catch(err => { console.log(‘err->’, err) })
2. Promise.race竞速方法
```javascript
let p1 = new Promise((resolve, reject) => {
resolve('ok1')
})
let p2 = new Promise((resolve, reject) => {
setTimeout(() => {resolve('ok2')}, 10)
})
Promise.race([p2, p1]).then((result) => {
console.log(result) //ok1
}).catch((error) => {
console.log(error)
})
**3. 当Promise链中抛出一个错误时,错误信息沿着链路向后传递,直至被捕获
Promise.resolve().then(() => {
console.log('ok1')
throw 'throw error1'
}).then(() => {
console.log('ok2')
}, err => {
// 捕获错误
console.log('err->', err)
}).then(() => {
// 该函数将被调用
console.log('ok3')
throw 'throw error3'
}).then(() => {
// 错误捕获前的函数不会被调用
console.log('ok4')
}).catch(err => {
console.log('err->', err)
})