forked from vuejs/vuepress
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAsyncOption.js
94 lines (80 loc) · 1.85 KB
/
AsyncOption.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
'use strict'
/**
* Module dependencies.
*/
const { logger, chalk, datatypes: { isFunction }} = require('@vuepress/shared-utils')
const Option = require('./Option')
/**
* Expose asynchronous option class.
*/
class AsyncOption extends Option {
/**
* Asynchronous serial running
*
* @param args
* @param {Array<AsyncFunction>} args
* @api public
*/
async asyncApply (...args) {
const rawItems = this.items
this.items = []
this.appliedItems = this.items
for (const { name, value } of rawItems) {
try {
this.add(
name,
isFunction(value)
? await Promise.resolve(value(...args))
: value
)
} catch (error) {
logger.error(`${chalk.cyan(name)} apply ${chalk.cyan(this.key)} failed.`)
throw error
}
}
this.items = rawItems
}
/**
* Asynchronous serial running
*
* @param args
* @param {Array<AsyncFunction>} args
* @api public
*/
async parallelApply (...args) {
const rawItems = this.items
this.items = []
this.appliedItems = this.items
await Promise.all(rawItems.map(async ({ name, value }) => {
try {
this.add(
name,
isFunction(value)
? await Promise.resolve(value(...args))
: value
)
} catch (error) {
logger.error(`${chalk.cyan(name)} apply ${chalk.cyan(this.key)} failed.`)
throw error
}
})).catch(error => {
throw error
})
this.items = rawItems
}
/**
* Process a value via a pipeline.
*
* @param input
* @returns {any}
* @api public
*/
async pipeline (input) {
for (const fn of this.values) {
input = await Promise.resolve(fn(input))
}
return input
}
}
AsyncOption.prototype.apply = AsyncOption.prototype.asyncApply
module.exports = AsyncOption