Promise
Demo1:
methods: {
startTodoTheProblem(){
this.answerQuestion().then((result)=> {
this.success(result)
}).catch((result)=>{
this.failure(result)
})
},
answerQuestion(){
return new Promise(function(resolve, reject){
const number = 2 + 3
number === 6 ? resolve('🍒') : reject('🐽')
})
},
success(value){
alert('回答正确️'+ value)
},
failure(value){
alert('回答错误'+ value)
}
}
//Promise.resolve() ,Promise.reject()
//---------------------------------------log
//🐽
Demo2:
methods: {
startCooking(){
function cutUp(){
console.log('Start cutting vegetables');
var result = new Promise(function(resolve, reject){ //做一些异步操作
setTimeout(function(){
console.log('Cut vegetables!');
resolve('🥕🥕🥕');
}, 1000);
});
return result;
}
function boil(){
console.log('Start boiling water');
var result = new Promise(function(resolve, reject){ //做一些异步操作
setTimeout(function(){
console.log('Boiling water!');
resolve('💧💧💧');
}, 3000);
});
return result;
}
Promise.all([cutUp(), boil()])
.then((result) => {
console.log('ready');
console.log(result);
})
.catch((error)={
//.........
}
)
}
}
//Promise.all()
//---------------------------------------log
//Start cutting vegetables
//Start boiling water
//Cut vegetables!
//Boiling water!
//["🥕🥕🥕", "💧💧💧"]
Demo3:
methods:{
startRunning(){
function tortoise(){
console.log('Tortoise Go');
var result = new Promise(function(resolve, reject){ //做一些异步操作
setTimeout(function(){
resolve('🐢');
}, 2000);
});
return result;
}
function rabbit(){
console.log('Rabbit Go!');
var result = new Promise(function(resolve, reject){ //做一些异步操作
setTimeout(function(){
resolve('🐇');
}, 1000);
});
return result;
}
Promise.race([tortoise(), rabbit()])
.then((result) => {
console.log(result + 'victory!!!');
})
.catch((error)={
//.........
}
)
}
}
//Promise.race()
//---------------------------------------log
// Tortoise Go
// Rabbit Go!
// 🐇victory!!!