UNPKG

@qiniu/miku-delivery-mp-ks

Version:

Kuaishou Mini Program SDK for Miku Delivery

64 lines (63 loc) 2.06 kB
/** * @file Mutex for async processing */ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; export default class Mutex { constructor() { Object.defineProperty(this, "locked", { enumerable: true, configurable: true, writable: true, value: false }); Object.defineProperty(this, "waitings", { enumerable: true, configurable: true, writable: true, value: [] }); this.unlock = this.unlock.bind(this); } lock() { return __awaiter(this, void 0, void 0, function* () { if (!this.locked) { this.locked = true; return this.unlock; } yield new Promise(resolve => { this.waitings.push(resolve); }); return this.unlock; }); } unlock() { if (this.waitings.length === 0) { this.locked = false; return; } const waiting = this.waitings.shift(); waiting(); } runExclusive(job) { return __awaiter(this, void 0, void 0, function* () { const unlock = yield this.lock(); try { return yield job(); } catch (e) { throw e; } finally { unlock(); } }); } }