JavaScript的非同步(async/await/promise)
我們知道,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 letjsonStr =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值更清晰的理解。