回调函数:就是将后续的逻辑传入到当前要做的事情中,事情做好后调用此函数。
let a='';
function buy(callback){
setTimeout(()=>{
a='白菜';
callback()
},2000)
}
buy(function cook(){
console.log(a);
})
这种模式看起来非常恶心,不容易代码的维护,那么promise的出现完美的解决了回调问题。
promise解决回调问题promise三个状态(成功,失败,等待)
resolve代表的是转向成功态
reject代表的是转向失败态
resolve和reject均为函数
promise的实例有一个then方法,then方法中有两个参数(两个回调函数)
let p=new Promise((resolve,reject)=>{
setTimeout(()=>{
let a='白菜';
resolve(a);
},2000)
});
p.then((data)=>{console.log(data)},()=>{})
function buyPack(){
return new Promise((resolve,reject)=>{
setTimeout(()=>{
if(Math.random()>0.5){
resolve('买');
}else{
reject('不买');
}
},100);
});
};
buyPack().then(function(data){ //成功的回调
console.log(data);
},function(data){ //失败的回调
console.log(data);