Promise

说明:
有了 Promise 对象,就可以将异步操作以同步操作的流程表达出来,避免了层层嵌套的回调函数。
Promise 构造函数包含一个参数和一个带有 resolve(解析)和 reject(拒绝)两个参数的回调。在回调中执行一些操作,如果执行成功,则调用 resolve(),失败调用 reject()。

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!!!
posted @ 2020-10-19 22:31  BingNiTer  阅读(90)  评论(3编辑  收藏  举报