vue使用promise、async、await的一点理解

理解:

Promise返回一个对象,这个对象的构造函数里面可以传入函数,函数的第一个参数是一个回调函数,即成功的回调函数。函数的第二个参数也是回调函数,失败的回调函数。这个对象可以.then().catch(),所以可以写成new Promise().then().catch(),也可以写成var a = new Promise(); a.then().catch();

Promise构造函数的参数是一个函数,函数里面的代码是异步的,即Promise里面的操作,和Promise()外面的操作时异步"同时"进行的,

Promise中的函数的第一个参数是回调函数,resolve用来触发then里面的代码,第二个参数是回调函数,reject用来触发catch中的代码,throw new Error();也可以触发catch,

await可以是Promise同步,即不会立即执行Proimse外面(或者说下面)的代码,而await只能用在async标记的函数中,这样async函数本身就是异步的,而async函数里面的代码是同步的

async本身是异步的,可以这样理解,async函数执行到await的时候就立即返回,开始执行async下面的代码,与await等待执行的代码同时执行

渐进理解:

    test:function(){
      new Promise((resolve, reject)=>{
        console.log('promise')
        setTimeout(()=>{
          console.log('time out')
          console.log(reject)
          reject(3455435)
        }, 1000)
      }).then(r=>{
        console.log('promise then')
        console.log(r)
      }).catch(e=>{
        console.log('promise catch')
        console.log(e)
      })
	  console.log('new Promise done')
    }, 

    //resolve和reject是两个回调函数,调用resolve会触发then,reject会触发catch

 


    

    test:function(){
      new Promise((resolve, reject)=>{
        console.log('promise')
        setTimeout(()=>{
          console.log('time out')
          console.log(resolve)
          resolve(3455435)
        }, 1000)
      }).then(r=>{
        console.log('promise then')
        throw new Error('我勒个去!');//触发catch
        console.log(r)
      }).catch(e=>{
        console.log('promise catch')
        console.log(e)
      })
    }, 

    //throw new Error('哈哈哈哈')也会触发catch

 


    

    test:function(){
      //做饭
      function cook(){
          console.log('开始做饭。');
          var p = new Promise(function(resolve, reject){        //做一些异步操作
              setTimeout(function(){
                  console.log('做饭完毕!');
                  resolve('鸡蛋炒饭');
              }, 1000);
          });
          return p;
      }
       
      //吃饭
      function eat(data){
          console.log('开始吃饭:' + data);
          var p = new Promise(function(resolve, reject){        //做一些异步操作
              setTimeout(function(){
                  console.log('吃饭完毕!');
                  resolve('一块碗和一双筷子');
              }, 2000);
          });
          return p;
      }
       
      function wash(data){
          console.log('开始洗碗:' + data);
          var p = new Promise(function(resolve, reject){        //做一些异步操作
              setTimeout(function(){
                  console.log('洗碗完毕!');
                  resolve('干净的碗筷');
              }, 2000);
          });
          return p;
      }

      cook()
      .then(function(data){
          return eat(data);
      })
      .then(function(data){
          return wash(data);
      })
      .then(function(data){
          console.log(data);
      });
      
      console.log('cook done????')
    }, 

    //new Promise返回到是一个对象,可以在对象后面加then,then要在resolve后才会触发,所以会顺序执行,但是它本身是异步的,所以没有.then的代码会是会异步执行

 


    
    

    test:function(){
      //做饭
      function cook(){
          console.log('开始做饭。');
          var p = new Promise(function(resolve, reject){        //做一些异步操作
              setTimeout(function(){
                  console.log('做饭失败!');
                  reject('烧焦的米饭');
              }, 1000);
          });
          return p;
      }
       
      //吃饭
      function eat(data){
          console.log('开始吃饭:' + data);
          var p = new Promise(function(resolve, reject){        //做一些异步操作
              setTimeout(function(){
                  console.log('吃饭完毕!');
                  resolve('一块碗和一双筷子');
              }, 2000);
          });
          return p;
      }
       
      cook()
      .then(eat, function(data){
        console.log(data + '没法吃!');
      })

      console.log('cooke done ???')
    }, 

    //reject 方法就是把 Promise 的状态置为已失败(Rejected),这时 then 方法执行“失败”情况的回调(then 方法的第二参数)。

 

 

    test:function(){
      async function testAsync(){
        return "hello async"
      }

      var a = testAsync();
      console.log(a)
      a.then((b)=>{
        console.log("a.then")
        console.log(b)
      })
    }, 

    //async返回的是一个Promise对象,then的第一个参数就是async函数的返回值

如果var a = await testAsync();返回值就是"hello async",因为await等待的就是Promise的返回,而async返回到就是一个Promise,然后这个Promise中直接返回了"hello async"

 

 

    test:function(){
      function takeLongTime() {
          return new Promise(resolve => {
              setTimeout(() => resolve("long_time_value"), 1000);
          });
      }

      async function test() {
          console.log('before takeLongTime')
          const v = await takeLongTime();
          console.log(v);
      }

      test();
      console.log('after test')

    }, 

    //await可以阻塞Promise对象,await=async wait,await只能出现在async函数内部

 

   

    async request(){

      var url = this.url

      var a = new Promise(resolve=>{
        this.axios.post(url, 
          postData
        ).then(res=>{
          console.log(res.data)
          resolve('请求成功')
        }).catch(error=>{
          console.log(error)
          resolve('请求失败')
        })
        console.log('new Promise done')
      })

      console.log('before await a')
      var b = await a
      console.log('await a done')
      console.log(b)
    }, 

    //使网络请求同步,但是仔细一看,其实axios.post也有then catch,所以可以有更简单的调用

    async request(){
      var url = this.url

      var a = this.axios.post(url, 
          postData, 
          {
            // 单独配置
            withCredentials: true
          }
        ).then(res=>{
          console.log(res.data)
          return '请求成功'
        }).catch(error=>{
          console.log(error)
          return '请求失败'
        })

      console.log('before await a')
      var b = await a
      console.log('await a done')
      console.log(b)
    }, 

或者写成request:async function(){}


    

  mounted:function(){

    console.log('test async')
    this.request()
    console.log('async done')
  }, 

  //async函数使其内部同步,同级调用还是异步,async函数下面的接口会在async函数中的await执行完之前调用

  • 5
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue 3.0 中,支持使用 Promiseasync/await 来处理异步操作。Vue 3.0 在对 Options API 进行重构的同时,也引入了 Composition API,这使得在组件中使用 Promiseasync/await 更加方便。 在 Vue 3.0 中,你可以使用 async/await 来编写异步操作。比如,你可以在组件的生命周期钩子函数中使用 async/await 来等待异步操作的完成,然后再继续执行其他逻辑。例如: ```javascript export default { async created() { try { const response = await fetch('https://api.example.com/data'); const data = await response.json(); // 处理获取到的数据 } catch (error) { // 处理错误 } } } ``` 在上面的例子中,我们使用async/await 来等待 fetch 请求的完成,并且将返回的数据解析为 JSON 格式。如果出现错误,我们也可以使用 try-catch 块来捕获并处理错误。 另外,Vue 3.0 还提供了一些便捷的方法来处理 Promise。比如,你可以使用 Vue 的 `$nextTick` 方法来等待 DOM 更新完成后再执行某些操作,而不需要手动创建 Promise。例如: ```javascript export default { methods: { async fetchData() { // 异步获取数据 await this.$nextTick(); // DOM 更新完成后执行某些操作 } } } ``` 上面的例子中,`fetchData` 方法中的 `this.$nextTick()` 返回一个 Promise,它会在 DOM 更新完成后 resolve。我们可以使用 await 来等待 DOM 更新完成后再执行某些操作。 总的来说,在 Vue 3.0 中,使用 Promiseasync/await 可以更方便地处理异步操作,使代码更加清晰和易于维护。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值