From 4d50c6b95f490fe6a143cf9a31d85e15cc3f9062 Mon Sep 17 00:00:00 2001 From: henryxue Date: Mon, 22 Aug 2022 22:34:54 +0800 Subject: [PATCH] =?UTF-8?q?feat:=E5=AE=8C=E6=88=90=E4=BD=9C=E4=B8=9A?= =?UTF-8?q?=EF=BC=8Ctapable2=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lib/db.js | 52 ++++++++++++++++++++++++++++++++++++++++++++++------ package.json | 3 ++- 2 files changed, 48 insertions(+), 7 deletions(-) diff --git a/lib/db.js b/lib/db.js index a1fe32c..38b9983 100644 --- a/lib/db.js +++ b/lib/db.js @@ -1,13 +1,53 @@ -const Tapable = require('tapable') +const { AsyncSeriesWaterfallHook, AsyncSeriesBailHook } = require("tapable"); -class DB extends Tapable { - constructor() { +class DB { + // options; + constructor(options) { // TODO + // super(); + this.options = options; + + this.hook = new AsyncSeriesWaterfallHook(["res"]); + /** + * 保存每一步回调操作的正常结果 + */ + this.values = []; } - request() { - // TODO + request(options) { + return new Promise((resolve, reject) => { + const finalOps = {}; + Object.assign(finalOps, options, this.options); + + this.hook.callAsync(finalOps, (err, res) => { + // judge一般都会是最后一个回调 + const prevRes = this.values.slice(0, this.values.length - 1).pop(); + + // err || err === undefined 验证reject空和非空 + // res === true 验证中断 + if (err || err === undefined || res === true) reject(prevRes); + else { + resolve(res); + } + }); + }); + } + + plugin(name, callback) { + this.hook.tapPromise(name, async (...args) => { + // 为了保存中间结果,返回new Promise + // 为了把同步回调都转成异步使用await + const res = await callback(...args); + + // console.log("callback", res); + //回调中返回的undefined不保存 + if (res !== undefined) this.values.push(res); + + return new Promise((resolve, reject) => { + resolve(res); + }); + }); } } -module.exports = DB \ No newline at end of file +module.exports = DB; diff --git a/package.json b/package.json index aad5780..c0e6d62 100644 --- a/package.json +++ b/package.json @@ -28,6 +28,7 @@ "webpack": "^3.5.3" }, "dependencies": { - "puppeteer": "^16.2.0" + "puppeteer": "^16.2.0", + "tapable": "^2.2.1" } }