自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

異步單例模式之不一樣的單例模式

開發(fā) 前端
創(chuàng)建實例需要一定的時間,創(chuàng)建期間,交出執(zhí)行權,創(chuàng)建完畢后,拿回執(zhí)行權,返回結(jié)果。

[[422320]]

本文轉(zhuǎn)載自微信公眾號「云的程序世界」,作者云的世界。轉(zhuǎn)載本文請聯(lián)系云的程序世界公眾號。

前言

單例模式大家都知道,異步單例又為何物。

異步單例:

創(chuàng)建實例需要一定的時間,創(chuàng)建期間,交出執(zhí)行權,創(chuàng)建完畢后,拿回執(zhí)行權,返回結(jié)果。

有人可能會吐槽,就這,其他方案分分鐘搞定。沒錯,沒有誰不可被替代。

這里主要表達的是一種編程思想,其能改變代碼風格, 特定情況下漂亮的解決問題。多一種手段,多一種選擇。

先一起來看一個栗子:

asyncInsCreator延時2秒創(chuàng)建一個對象;

getAsyncIns 封裝異步對象獲取過程;

我們多次調(diào)用 getAsyncIns, 得到同一個對象。

  1. async function asyncInsCreator() { 
  2.     await delay(2000).run(); 
  3.     return new Object(); 
  4.  
  5. function getAsyncIns() { 
  6.     return factory(asyncInsCreator); 
  7.  
  8. ; (async function test() { 
  9.     try {   
  10.         const [ins1, ins2, ins3] = await Promise.all([ 
  11.             getAsyncIns(), 
  12.             getAsyncIns(), 
  13.             getAsyncIns() 
  14.         ]); 
  15.  
  16.         console.log("ins1:", ins1);  // ins1: {} 
  17.         console.log("ins1===ins2", ins1 === ins2); // ins1===ins2 true 
  18.         console.log("ins2===ins3", ins2 === ins3); // ins2===ins3 true 
  19.         console.log("ins3=== ins1", ins3 === ins1); // ins3=== ins1 true 
  20.     } catch (err) { 
  21.         console.log("err", err); 
  22.     } 
  23. })(); 

適用場景

異步單例

比如初始化socket.io客戶端, indexedDB等等

僅僅一次的情況

舉一個例子,我們可以注冊多個 load事件

  1. window.addEventListener("load"function () { 
  2.      // other code 
  3.      console.log("load 1"); 
  4. }); 
  5.  
  6. window.addEventListener("load"function () { 
  7.      // other code 
  8.      console.log("load 2"); 
  9. ); 

這要是換做React或者Vue,你先得訂閱還得取消訂閱,顯得麻煩,當然你可以利用訂閱發(fā)布思想再包裝一層:

如果換成如下,是不是賞心悅目:

  1. await loaded(); 
  2. // TODO::   

你肯定說,這個我會:

  1. function loaded() { 
  2.        return new Promise((resove, reject) => { 
  3.            window.addEventListener("load", resove) 
  4.        }); 
  5.    } 

我給你一段測試代碼:

下面只會輸出 loaded 1,不會輸出loaded 2。

至于原因:load事件只會觸發(fā)一次。

  1. function loaded() { 
  2.     return new Promise((resolve, reject) => { 
  3.         window.addEventListener("load", ()=> resolve(null)); 
  4.     }); 
  5.  
  6. async function test() { 
  7.     await loaded(); 
  8.     console.log("loaded 1"); 
  9.      
  10.     setTimeout(async () => { 
  11.         await loaded(); 
  12.         console.log("loaded 2"); 
  13.     }, 1000) 
  14.  
  15. est(); 

到這里,我們的異步單例就可以秀一把,雖然他本意不是干這個,但他可以,因為他滿足僅僅一次的條件。

我們看看使用異步單例模式的代碼:

loaded 1 與 loaded 2 都如期到來。

  1. const factory = asyncFactory(); 
  2.  
  3. function asyncInsCreator() { 
  4.     return new Promise((resove, reject) => { 
  5.         window.addEventListener("load", ) 
  6.     }); 
  7.  
  8. function loaded() { 
  9.     return factory(asyncInsCreator) 
  10.  
  11. async function test() { 
  12.     await loaded(); 
  13.     console.log("loaded 1");  // loaded 1 
  14.  
  15.     setTimeout(async () => { 
  16.         await loaded(); 
  17.         console.log("loaded 2"); // loaded 2 
  18.     }, 1000) 
  19.  
  20. test(); 

實現(xiàn)思路

狀態(tài)

實例創(chuàng)建,其實也就只有簡簡單單的兩種狀態(tài):

  1. 創(chuàng)建中
  2. 創(chuàng)建完畢

難點在于,創(chuàng)建中的時候,又有新的請求來獲取實例。

那么我們就需要一個隊列或者數(shù)組來維護這些請求隊列,等待實例創(chuàng)建完畢,再通知請求方。

如果實例化已經(jīng)完畢,那么之后就直接返回實例就好了。

變量

我們這里就需要三個變量:

  1. instance 存儲已經(jīng)創(chuàng)建完畢的實例
  2. initializing 是否創(chuàng)建中
  3. requests 來保存哪些處于創(chuàng)建中,發(fā)過來的請求

工具方法

delay:

延時一定時間調(diào)用指定的函數(shù)。

用于后面的超時,和模擬延時。

  1. export function delay(delay: number = 5000, fn = () => { }, context = null) { 
  2.     let ticket = null
  3.     return { 
  4.         run(...args: any[]) { 
  5.             return new Promise((resolve, reject) => { 
  6.                 ticket = setTimeout(async () => { 
  7.                     try { 
  8.                         const res = await fn.apply(context, args); 
  9.                         resolve(res); 
  10.                     } catch (err) { 
  11.                         reject(err); 
  12.                     } 
  13.                 }, delay); 
  14.             }); 
  15.         }, 
  16.         cancel: () => { 
  17.             clearTimeout(ticket); 
  18.         } 
  19.     }; 
  20. }; 

基礎版本

實現(xiàn)代碼

注意點:

1.instance !== undefined這個作為判斷是否實例化,也就是說可以是null, 僅僅一次的場景下使用,最適合不過了。

這里也是一個局限,如果就是返回undefined呢, 我保持沉默。

2.有人可能會吐槽我,你之前還說過 undefined不可靠,我微微一笑,你覺得迷人嗎?

失敗之后 initializing = false這個意圖,就是某次初始化失敗時,會通知之前的全部請求,已失敗。

之后的請求,還會嘗試初始化。

  1. import { delay } from "../util"
  2.  
  3. function asyncFactory() { 
  4.     let requests = []; 
  5.     let instance; 
  6.     let initializing = false
  7.  
  8.     return function initiator(fn: (...args: any) => Promise<any>) { 
  9.          // 實例已經(jīng)實例化過了 
  10.          if (instance !== undefined){ 
  11.             return Promise.resolve(instance); 
  12.         } 
  13.         // 初始化中 
  14.         if (initializing) { 
  15.             return new Promise((resolve, reject) => { 
  16.                 // 保存請求 
  17.                 requests.push({ 
  18.                     resolve, 
  19.                     reject 
  20.                 }); 
  21.             }) 
  22.         } 
  23.         initializing = true
  24.         return new Promise((resolve, reject) => { 
  25.             // 保存請求 
  26.             requests.push({ 
  27.                 resolve, 
  28.                 reject 
  29.             }); 
  30.  
  31.             fn() 
  32.                 .then(result => { 
  33.                     instance = result; 
  34.                     initializing = false
  35.                     processRequests('resolve', instance); 
  36.                 }) 
  37.                 .catch(error => { 
  38.                     initializing = false
  39.                     processRequests('reject', error); 
  40.                 }); 
  41.         }); 
  42.     } 
  43.     function processRequests(type: "resolve" | "reject", value: any) { 
  44.         // 挨個resolve 
  45.         requests.forEach(q => { 
  46.             q[type](value "type"); 
  47.         }); 
  48.         // 置空請求,之后直接用instance 
  49.         requests = []; 
  50.     } 

測試代碼

  1. const factory = asyncFactory(); 
  2.  
  3. async function asyncInsCreator() { 
  4.     await delay(2000).run(); 
  5.     return new Object(); 
  6.  
  7. function getAsyncIns() { 
  8.     return factory(asyncInsCreator); 
  9.  
  10. ; (async function test() { 
  11.     try {   
  12.  
  13.         const [ins1, ins2, ins3] = await Promise.all([ 
  14.             getAsyncIns(), 
  15.             getAsyncIns(), 
  16.             getAsyncIns() 
  17.         ]); 
  18.  
  19.         console.log("ins1:", ins1);  // ins1: {} 
  20.         console.log("ins1===ins2", ins1 === ins2); // ins1===ins2 true 
  21.         console.log("ins2===ins3", ins2 === ins3); // ins2===ins3 true 
  22.         console.log("ins3=== ins1", ins3 === ins1); // ins3=== ins1 true 
  23.     } catch (err) { 
  24.         console.log("err", err); 
  25.     } 
  26.  
  27. })(); 

存在的問題:

沒法傳參啊,沒法設置this的上下文啊。

傳遞參數(shù)版本

實現(xiàn)思路:

  1. 增加參數(shù) context 以及 args參數(shù)
  2. Function.prototype.appy

實現(xiàn)代碼

  1. import { delay } from "../util"
  2.  
  3. interface AVFunction<T = unknown> { 
  4.     (value: T): void 
  5.  
  6. function asyncFactory<R = unknown, RR = unknown>() { 
  7.     let requests: { reject: AVFunction<RR>, resolve: AVFunction<R> }[] = []; 
  8.     let instance: R; 
  9.     let initializing = false
  10.  
  11.     return function initiator(fn: (...args: any) => Promise<R>,  
  12.     context: unknown, ...args: unknown[]): Promise<R> { 
  13.         // 實例已經(jīng)實例化過了 
  14.         if (instance !== undefined){ 
  15.             return Promise.resolve(instance); 
  16.         } 
  17.         // 初始化中 
  18.         if (initializing) { 
  19.             return new Promise((resolve, reject) => { 
  20.                 requests.push({ 
  21.                     resolve, 
  22.                     reject 
  23.                 }) 
  24.             }) 
  25.         } 
  26.         initializing = true 
  27.         return new Promise((resolve, reject) => { 
  28.             requests.push({ 
  29.                 resolve, 
  30.                 reject 
  31.             }) 
  32.  
  33.             fn.apply(context, args) 
  34.                 .then(res => { 
  35.                     instance = res; 
  36.                     initializing = false
  37.                     processRequests('resolve', instance); 
  38.                 }) 
  39.                 .catch(error => { 
  40.                     initializing = false
  41.                     processRequests('reject', error); 
  42.                 }) 
  43.         }) 
  44.     } 
  45.  
  46.     function processRequests(type: "resolve" | "reject", value: any) { 
  47.         // 挨個resolve 
  48.         requests.forEach(q => { 
  49.             q[type](value "type"); 
  50.         }); 
  51.         // 置空請求,之后直接用instance 
  52.         requests = []; 
  53.     } 

測試代碼

  1. interface RES { 
  2.     p1: number 
  3.  
  4. const factory = asyncFactory<RES>(); 
  5.  
  6. async function asyncInsCreator(opitons: unknown = {}) { 
  7.     await delay(2000).run(); 
  8.     console.log("context.name", this.name); 
  9.     const result = new Object(opitons) as RES; 
  10.     return result; 
  11.  
  12. function getAsyncIns(context: unknown, options: unknown = {}) { 
  13.     return factory(asyncInsCreator, context, options); 
  14.  
  15. ; (async function test() { 
  16.  
  17.     try { 
  18.         const context = { 
  19.             name"context" 
  20.         }; 
  21.  
  22.         const [ins1, ins2, ins3] = await Promise.all([ 
  23.             getAsyncIns(context, { p1: 1 }), 
  24.             getAsyncIns(context, { p1: 2 }), 
  25.             getAsyncIns(context, { p1: 3 }) 
  26.         ]); 
  27.  
  28.         console.log("ins1:", ins1, ins1.p1); 
  29.         console.log("ins1=== ins2", ins1 === ins2); 
  30.         console.log("ins2=== ins3", ins2 === ins3); 
  31.         console.log("ins3=== ins1", ins3 === ins1); 
  32.     } catch (err) { 
  33.         console.log("err", err); 
  34.     } 
  35.  
  36. })(); 

存在的問題

看似完美,要是超時了,怎么辦呢?

想到這個問題的人,品論區(qū)發(fā)文,我給你們點贊。

超時版本

這里就需要借用我們的工具方法delay:

  • 如果超時沒有成功,通知所有請求失敗。
  • 反之,通知所有請求成功。

實現(xiàn)代碼

  1. import { delay } from "../util"
  2.  
  3. interface AVFunction<T = unknown> { 
  4.     (value: T): void 
  5.  
  6. function asyncFactory<R = unknown, RR = unknown>(timeout: number = 5 * 1000) { 
  7.     let requests: { reject: AVFunction<RR>, resolve: AVFunction<R> }[] = []; 
  8.     let instance: R; 
  9.     let initializing = false
  10.  
  11.     return function initiator(fn: (...args: any) => Promise<R>, context: unknown, ...args: unknown[]): Promise<R> { 
  12.  
  13.         // 實例已經(jīng)實例化過了 
  14.         if (instance !== undefined){ 
  15.             return Promise.resolve(instance); 
  16.         } 
  17.  
  18.         // 初始化中 
  19.         if (initializing) { 
  20.             return new Promise((resolve, reject) => { 
  21.                 requests.push({ 
  22.                     resolve, 
  23.                     reject 
  24.                 }) 
  25.             }) 
  26.         } 
  27.  
  28.         initializing = true 
  29.         return new Promise((resolve, reject) => { 
  30.  
  31.             requests.push({ 
  32.                 resolve, 
  33.                 reject 
  34.             }) 
  35.  
  36.             const { run, cancel } = delay(timeout); 
  37.  
  38.             run().then(() => { 
  39.                 const error = new Error("操作超時"); 
  40.                 processRequests("reject", error); 
  41.             }); 
  42.  
  43.             fn.apply(context, args) 
  44.                 .then(res => { 
  45.                     // 初始化成功 
  46.                     cancel(); 
  47.                     instance = res; 
  48.                     initializing = false
  49.                     processRequests('resolve', instance); 
  50.                 }) 
  51.                 .catch(error => { 
  52.                     // 初始化失敗 
  53.                     cancel(); 
  54.                     initializing = false
  55.                     processRequests('reject', error); 
  56.                 }) 
  57.         }) 
  58.     } 
  59.  
  60.     function processRequests(type: "resolve" | "reject", value: any) { 
  61.         // 挨個resolve 
  62.         requests.forEach(q => { 
  63.             q[type](value "type"); 
  64.         }); 
  65.         // 置空請求,之后直接用instance 
  66.         requests = []; 
  67.     } 
  68.  
  69. interface RES { 
  70.     p1: number 
  71. const factory = asyncFactory<RES>(); 
  72.  
  73. async function asyncInsCreator(opitons: unknown = {}) { 
  74.     await delay(1000).run(); 
  75.     console.log("context.name", this.name); 
  76.     const result = new Object(opitons) as RES; 
  77.     return result; 
  78.  
  79. function getAsyncIns(context: unknown, options: unknown = {}) { 
  80.     return factory(asyncInsCreator, context, options); 
  81. ; (async function test() { 
  82.  
  83.     try { 
  84.         const context = { 
  85.             name"context" 
  86.         }; 
  87.  
  88.         const [instance1, instance2, instance3] = await Promise.all([ 
  89.             getAsyncIns(context, { p1: 1 }), 
  90.             getAsyncIns(context, { p1: 2 }), 
  91.             getAsyncIns(context, { p1: 3 }) 
  92.         ]); 
  93.  
  94.         console.log("instance1:", instance1, instance1.p1); 
  95.         console.log("instance1=== instance2", instance1 === instance2); 
  96.         console.log("instance2=== instance3", instance2 === instance3); 
  97.         console.log("instance3=== instance1", instance3 === instance1); 
  98.     } catch (err) { 
  99.         console.log("err", err); 
  100.     } 
  101. })(); 

測試代碼

當把asyncInsCreator的 delay(1000)修改為 delay(6000)的時候,創(chuàng)建所以的事件6000ms大于 asyncFactory默認的5000ms,就會拋出下面的異常。

  1. err Error: 操作超時 
  2.     at c:\projects-github\juejinBlogs\異步單例\queue\args_timeout.ts:40:31 
  1. interface RES { 
  2.     p1: number 
  3.  
  4. const factory = asyncFactory<RES>(); 
  5.  
  6.  
  7. async function asyncInsCreator(opitons: unknown = {}) { 
  8.     await delay(1000).run(); 
  9.     console.log("context.name", this.name); 
  10.     const result = new Object(opitons) as RES; 
  11.     return result; 
  12.  
  13. function getAsyncIns(context: unknown, options: unknown = {}) { 
  14.     return factory(asyncInsCreator, context, options); 
  15.  
  16. ; (async function test() { 
  17.     try { 
  18.         const context = { 
  19.             name"context" 
  20.         }; 
  21.         const [ins1, ins2, ins3] = await Promise.all([ 
  22.             getAsyncIns(context, { p1: 1 }), 
  23.             getAsyncIns(context, { p1: 2 }), 
  24.             getAsyncIns(context, { p1: 3 }) 
  25.         ]); 
  26.  
  27.         console.log("ins1:", ins1, ins1.p1); 
  28.         console.log("ins1=== ins2", ins1 === ins2); 
  29.         console.log("ins2=== ins3", ins2 === ins3); 
  30.         console.log("ins3=== ins1", ins3 === ins1); 
  31.     } catch (err) { 
  32.         console.log("err", err); 
  33.     } 
  34. })(); 

存在的問題

存在的問題:

  1. 拋出了的Error new Error("操作超時")我們簡單粗暴的拋出了這個異常,當外圍的try/catch捕獲后,還沒法區(qū)別這個錯誤的來源。我們可以再封住一個AsyncFactoryError,或者 asyncInsCreator 拋出特定一定,交給try/catch 自身去識別。
  2. 沒有判斷參數(shù) fn如果不是一個有效的函數(shù),fn執(zhí)行后是不是一個返回Promise。

是不是一個有效的函數(shù)好判斷。

執(zhí)行后是不是返回一個Promise, 借巨人p-is-promise[1]肩膀一靠。

  1. // 核心代碼 
  2. function isPromise(value) { 
  3.    return value instanceof Promise || 
  4.     ( 
  5.      isObject(value) && 
  6.      typeof value.then === 'function' && 
  7.      typeof value.catch === 'function' 
  8.     ); 

存在問題,你就不解決了嗎?不解決,等你來動手。

基于訂閱發(fā)布模式的版本

這里是實現(xiàn)的另外一種思路, 利用訂閱發(fā)布者。

要點

通過在Promise監(jiān)聽EventEmitter事件, 這里因為只需要監(jiān)聽一次,once閃亮登場。

  1. new Promise((resolve, reject) => { 
  2.     emitter.once("initialized", () => { 
  3.         resolve(instance); 
  4.     }); 
  5.     emitter.once("error", (error) => { 
  6.         reject(error); 
  7.     }); 
  8. }); 

實現(xiàn)代碼

這里就實現(xiàn)一個最基礎版本,至于帶上下文,參數(shù),超時的版本,大家可以嘗試自己實現(xiàn)。

  1. import { EventEmitter } from "events"
  2. import { delay } from "./util"
  3.  
  4. function asyncFactory<R = any>() { 
  5.     let emitter = new EventEmitter(); 
  6.     let instance: any = null
  7.     let initializing = false
  8.  
  9.     return function getAsyncInstance(factory: () => Promise<R>): Promise<R> { 
  10.         // 已初始化完畢 
  11.         if (instance !== undefined){ 
  12.             return Promise.resolve(instance); 
  13.         } 
  14.         // 初始化中 
  15.         if (initializing === true) { 
  16.             return new Promise((resolve, reject) => { 
  17.                 emitter.once("initialized", () => { 
  18.                     resolve(instance); 
  19.                 }); 
  20.                 emitter.once("error", (error) => { 
  21.                     reject(error); 
  22.                 }); 
  23.             }); 
  24.         } 
  25.  
  26.         initializing = true
  27.         return new Promise((resolve, reject) => { 
  28.             emitter.once("initialized", () => { 
  29.                 resolve(instance); 
  30.             }); 
  31.             emitter.once("error", (error) => { 
  32.                 reject(error); 
  33.             }); 
  34.             factory() 
  35.                 .then(ins => { 
  36.                     instance = ins; 
  37.                     initializing = false
  38.                     emitter.emit("initialized"); 
  39.                     emitter = null
  40.                 }) 
  41.                 .catch((error) => { 
  42.                     initializing = false
  43.                     emitter.emit("error", error); 
  44.                 }); 
  45.         }) 
  46.     } 

總結(jié)

異步單例不多見,這里要表達的是一種思想,把基于事件的編程,變?yōu)榛赑romise的編程。

這里其實還涉及一些設計模式, 學以致用,投入實際代碼中,解決問題,帶來收益,這才是我們追求的。

async-init[2]

Is it impossible to create a reliable async singleton pattern in JavaScript?[3]

Creating an async singletone in javascript[4]

參考資料

[1]p-is-promise: https://www.npmjs.com/package/p-is-promise

[2]async-init: https://github.com/ert78gb/async-init

[3]Is it impossible to create a reliable async singleton pattern in JavaScript?: https://stackoverflow.com/questions/58919867/is-it-impossible-to-create-a-reliable-async-singleton-pattern-in-javascript

[4]Creating an async singletone in javascript: https://stackoverflow.com/questions/59612076/creating-an-async-singletone-in-javascript

 

責任編輯:武曉燕 來源: 云的程序世界
相關推薦

2016-03-28 10:23:11

Android設計單例

2023-06-05 07:55:31

2022-06-07 08:55:04

Golang單例模式語言

2021-03-02 08:50:31

設計單例模式

2021-02-01 10:01:58

設計模式 Java單例模式

2015-09-06 11:07:52

C++設計模式單例模式

2022-09-29 08:39:37

架構

2013-11-26 16:20:26

Android設計模式

2022-02-06 22:30:36

前端設計模式

2024-02-04 12:04:17

2021-02-07 23:58:10

單例模式對象

2011-03-16 10:13:31

java單例模式

2024-03-06 13:19:19

工廠模式Python函數(shù)

2016-10-09 09:37:49

javascript單例模式

2023-11-21 21:39:38

單例模式音頻管理器

2011-06-28 15:18:45

Qt 單例模式

2019-06-11 09:50:07

SparkBroadcast代碼

2012-03-07 17:24:10

戴爾咨詢

2012-12-20 10:17:32

IT運維

2021-08-11 17:22:11

設計模式單例
點贊
收藏

51CTO技術棧公眾號