npm install e-promise
# or
yarn add e-promise
複製代碼
在 Node 中,咱們常常須要鏈接數據庫、Redis、Mq、Socket、Rpc等等,它們都是基於回調通知是否鏈接成功,在鏈接成功的時候才能進行對應的操做,EventPromise 就是專門爲了解決它而存在,讓你使用同步的形式調用異步的回調。javascript
// 這裏用 socket.io 舉個例子,其它的觸類旁通
const EventPromise = require('e-promise');
class IoEventPromise extends EventPromise {
constructor() {
super({
// 設置超時時間,若是超過爲異常
timeout: 1000,
// 設置 awaitPromise 最大的調用次數,若是超過爲異常
maxCall: 100
});
const server = require('http').createServer();
const io = require('socket.io')(server);
io.on('connection', client => {
client.on('disconnect', () => {
// 鏈接失敗
this.emitError('disconnect');
});
// 鏈接成功
this.emitSuccess(client);
});
server.listen(3000);
}
async emit (eventName, ...args) {
const client = await this.awaitPromise();
// 鏈接失敗,則直接輸出錯誤
if (!client || typeof client === 'string') {
console.log(client);
return;
}
// 鏈接成功,直接發送事件
client.emit(eventName, ...args);
}
}
const io = new IoEventPromise();
// 這裏你就能夠當即調用,發送事件,等 socket 鏈接成功後自行發送
io.emit('事件名稱', '發送的參數');
複製代碼
eventPromise.emit(status: boolean, value: any = null);java
status = true 的狀況下,任什麼時候候都會直接響應 Promise
eventPromise.emitSuccess(value?: any);git
eventPromise.emitError(value?: any);github
eventPromise.awaitPromise();數據庫
GitHub 傳送門npm