- 回調函數
- Promise
- Rxjs
1、回調函數
1 /* 利用回調函數執行異步操作 */ 2 getCallBackData(callback) { // 把函數作為參數傳遞進去 3 setTimeout(() => { 4 let data = 'this is callback data'; 5 callback(data); // 將異步數據作為參數傳遞給函數 6 }, 1000) 7 } 8 9 10 /* 函數的調用----獲取 callback data */ 11 this.getCallBackData((result) => { 12 console.log(result); // 回調函數只能在傳入函數(參數)中處理 13 });
2、Promise
1 /* Promise */ 2 getPromiseData() { 3 return new Promise((resolve, reject) => { 4 setTimeout(() => { 5 const data = 'this is Promise data'; 6 resolve(data); // 將異步數據及相關操作封裝在 Promise對象中,通過resolve返回 7 }, 3000) 8 }) 9 } 10 11 12 /* 獲取 promise data */ 13 const promiseData = this.getPromiseData() 14 promiseData.then(x => { 15 console.log(x); 16 })
3、Rxjs
1 /* rxjs */ 2 getRxjsData() { 3 return new Observable(observer => { 4 setTimeout(() => { 5 const data = 'this is rxjs data'; 6 observer.next(data); // 將異步數據及相關操作封裝在 Observable 中,通過next返回 7 }, 3000); 8 }) 9 } 10 11 12 /* 獲取 rxjs data */ 13 const rxjsData = this.request.getRxjsData(); 14 const stream = rxjsData.subscribe(x => { // 將 subscribe 返回的subscription賦值給一個變量,取消訂閱要通過返回的subscription來取消 15 console.log(x); 16 });
注意:不管是通過 Promise 的 resolve返回,還是通過 getRxjsData 的 observer 返回,返回的時間用戶都不能馬上得到,必須分別使用 then 和 subscribe 來訂閱
4、Rxjs取消訂閱
1 /* 取消訂閱 3s后返回rxjs data,但是剛過1s,我想取消,不想訂閱了 */ 2 setTimeout(() => { 3 stream.unsubscribe(); // promise創建之后動作無法撤回,而Observable可以撤回發出的動作 4 }, 1000)
5、rxjs訂閱后多次執行
1 getMutipleRxjsData() { 2 return new Observable(observer => { 3 let count = 0; 4 setInterval(() => { 5 observer.next(count++); 6 // 對於 promise來說,最終結果要么是resolve或者reject,而且都只能觸發一次,如果在同一個promise對象上多次調用resolve方法,則會拋出異常 7 // 而Observable不一樣,它可以通過next方法源源不斷的觸發下一個值 8 }, 1000); 9 }) 10 } 11 12 13 /* rxjs 多次執行 */ 14 this.getMutipleRxjsData().subscribe(x => { 15 console.log(x); 16 })