1. 注意事项
- promise 通过new 实例或 Promise.resolve()的方式进行定义
- promise 是处理异步请求的,因为用户的需求在变,而且在处理异步的情况时,下一步的异步请求会用到上一步的异步请求的结果 。这个时候,使用promise来处理这种情况,避免“回调地狱”。
- 处理异步的方式:promise、回调函数、事件。**
2. 简单的实现
function BuyCai (resolve,reject){
setTimeout(()=>{
resolve(['西红柿','鸡蛋','黄瓜']);
},3000);
}
function ZuoCai (resolve,reject){
setTimeout(()=>{
resolve(['西红柿炒鸡蛋','鸡蛋炒西红柿']);
},3000)
}
function SongCai (resolve,reject){
setTimeout(()=>{
resolve('送菜完毕');
},3000);
}
function Tel (resolve,reject){
setTimeout(()=>{
resolve('支付tip');
},3000)
}
new Promise(BuyCai)
.then((resolve)=>{
console.log(resolve); //(3) ["西红柿", "鸡蛋", "黄瓜"]
return new Promise(ZuoCai)
}).then((resolve)=>{
console.log(resolve); //(2) ["西红柿炒鸡蛋", "鸡蛋炒黄瓜"]
return new Promise(SongCai)
}).then((resolve)=>{
console.log(resolve); //送菜完毕
return new Promise(Tel)
}).then((resolve)=>{
console.log(resolve); //支付tip
}).catch((err)=>{
console.log("message错误信息"+err);
});
3. promise.race()
var k1 = new Promise(function(resolve){
setTimeout(()=>{
resolve("k1 resolved");
},3000)
});
var k2 = new Promise(function(resolve,reject){
setTimeout(()=>{
resolve('k2 rejected');
},2000)
});
var k3 = new Promise(function(resolve,reject){
setTimeout(()=>{
reject("k3 resolved");
},1000)
});
这里的promise.race([k1,k2,k3]) 是指将内部的promise异步操作,按照(谁先执行完,结果显示谁,不管是成功还是失败)来操作。
Promise.race([k1,k2,k3])
.then(function(value){
console.log("k resolved, 得到的参数为:"+value);
})
.catch(function(error){
console.log("k rejected,"+error);
});
//运行结果:"k rejected , k3 resolved"