我们知道, JavaScript 是单线程, 为什么还要讲它的异步, 以及异步是怎么实现的, 本文不做细讲, 可以参阅 JavaScript 异步机制详解 https://juejin.im/post/5a6ad46ef265da3e513352c8 . 本文主要讲 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 对象 http://es6.ruanyifeng.com/#docs/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 值更清晰的理解.
来源: http://www.jianshu.com/p/c198638d70e3