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:this
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!!!