美文网首页程序员React Native开发经验集
JavaScript的异步(async/await/promis

JavaScript的异步(async/await/promis

作者: 码工人生 | 来源:发表于2019-03-09 19:34 被阅读35次

    我们知道,JavaScript是单线程,为什么还要讲它的异步,以及异步是怎么实现的,本文不做细讲,可以参阅JavaScript异步机制详解。本文主要讲JavaScript的异步的使用方法,使用ReactNative语言进行举例,主要讲async/await以及promise使用。
    一、async/await使用
    1.async/await,有await的地方一定有async。一个async对应一个或者多个await。
    2.await用来等待接受一个耗时的,异步的信号。await之后的代码,一定是在await接收到异步信号才会执行的。await使异步变得像同步。

    举例1
    testZeroMethod= async()=>{
        try {
            // 注意这里的await语句,其所在的函数必须有async关键字声明
            let response = await fetch(
              'https://facebook.github.io/react-native/movies.json',
            );
           //await 等到结果后才会走到这里
            console.log(response)
          } catch (error) {
            console.error(error);
          }
      }
    

    3.不使用async/await的异步调用。比如有些是系统底层方法,是没法在方法前加async的,这个时候就可以使用.then() .catch()

    举例2
     testOneMethod= ()=>{
            fetch('https://facebook.github.io/react-native/movies.json')
           .then((response)=>{
               console.log(response)
           })
           .catch((error)=>{
            console.error(error)
           })
      }
    

    二.Promise。 Promise的含义,以及基本语法,本文不再细讲,可以参考阮一峰老师Promise 对象,讲的很细。
    Promise是干嘛的,就是来实现异步的,是异步的核心。上面的举例1、举例2中的fetch和promise作用就很像。Promise想容器一样,把耗时的操作放在自己里面,不管过程是怎样,最终只通知结果给外部。
    1.定义一个Promise

    举例3
    testTwoMethod = (data)=>{
       let promise = new Promise ((resolve,reject)=>{
           let person = data||{name:"Jesse",age:30};
        //假如这是一个耗时操作JSON.stringify
           let  jsonStr =JSON.stringify(person);
              if(jsonStr){
                  resolve(jsonStr)
              }else{
                 reject()
              }
          
       })
       return promise;
    }
    

    2.async/await和promise的结合使用

    举例4
    testThreeMethod = async()=>{
      let data = {name:'Jim',age:18};
     //调用举例3的方法
      let result = await this.testTwoMethod(data);
      console.log(result); 
    }
    

    3.then()和.catch()与promise的结合

    举例5
    testFourMethod = ()=>{
      let data = {name:'Kin',age:50};
      this.testTwoMethod(data).then((result)=>{
          console.log(result); 
      }).catch((error)=>{
          console.log(error); 
      })
      
    }
    

    JavaScript中的异步很常见,新手很容易迷惑。我提供下本文的代码地址,有兴趣的可以下载代码,通过log值更清晰的理解。

    相关文章

      网友评论

        本文标题:JavaScript的异步(async/await/promis

        本文链接:https://www.haomeiwen.com/subject/mqkepqtx.html