Skip to content

Commit 3ffcd83

Browse files
anthony-redFoxjohnjbarton
authored andcommitted
feat: Preprocessor can return Promise (#3376)
preprocessor plugins can execute 'done()' or return a Promise
1 parent f8005c6 commit 3ffcd83

File tree

1 file changed

+30
-21
lines changed

1 file changed

+30
-21
lines changed

lib/preprocessor.js

Lines changed: 30 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -8,29 +8,39 @@ const CryptoUtils = require('./utils/crypto-utils')
88

99
const log = require('./logger').create('preprocess')
1010

11-
function createNextProcessor (preprocessors, file, done) {
12-
return function nextPreprocessor (error, content) {
13-
// normalize B-C
14-
if (arguments.length === 1 && typeof error === 'string') {
15-
content = error
16-
error = null
17-
}
18-
19-
if (error) {
20-
file.content = null
21-
file.contentPath = null
22-
return done(error)
11+
function executeProcessor (process, file, content) {
12+
let done = null
13+
const donePromise = new Promise((resolve, reject) => {
14+
done = function (error, content) {
15+
// normalize B-C
16+
if (arguments.length === 1 && typeof error === 'string') {
17+
content = error
18+
error = null
19+
}
20+
if (error) {
21+
reject(error)
22+
} else {
23+
resolve(content)
24+
}
2325
}
26+
})
27+
return process(content, file, done) || donePromise
28+
}
2429

25-
if (!preprocessors.length) {
26-
file.contentPath = null
27-
file.content = content
28-
file.sha = CryptoUtils.sha1(content)
29-
return done()
30+
async function runProcessors (preprocessors, file, content) {
31+
try {
32+
for (let process of preprocessors) {
33+
content = await executeProcessor(process, file, content)
3034
}
31-
32-
preprocessors.shift()(content, file, nextPreprocessor)
35+
} catch (error) {
36+
file.contentPath = null
37+
file.content = null
38+
throw error
3339
}
40+
41+
file.contentPath = null
42+
file.content = content
43+
file.sha = CryptoUtils.sha1(content)
3444
}
3545

3646
function createPriorityPreprocessor (config, preprocessorPriority, basePath, injector) {
@@ -103,7 +113,6 @@ function createPriorityPreprocessor (config, preprocessorPriority, basePath, inj
103113
.map((duo) => duo[0])
104114

105115
let preprocessors = []
106-
const nextPreprocessor = createNextProcessor(preprocessors, file, done)
107116
sortedPreprocessorNames.forEach((name) => {
108117
const p = instances[name] || instantiatePreprocessor(name)
109118

@@ -124,7 +133,7 @@ function createPriorityPreprocessor (config, preprocessorPriority, basePath, inj
124133
}
125134
})
126135

127-
nextPreprocessor(null, isBinary ? buffer : buffer.toString())
136+
runProcessors(preprocessors, file, isBinary ? buffer : buffer.toString()).then(done, done)
128137
})
129138
}
130139
return fs.readFile(file.originalPath, readFileCallback)

0 commit comments

Comments
 (0)