forked from CaptainN/npdev-react-loadable
-
Notifications
You must be signed in to change notification settings - Fork 0
/
react-loadable-both.js
95 lines (78 loc) · 1.67 KB
/
react-loadable-both.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
95
import React from 'react'
export function load (loader) {
const promise = loader()
const state = {
loading: true,
loaded: null,
error: null
}
state.promise = promise
.then(loaded => {
state.loading = false
state.loaded = loaded
return loaded
})
.catch(err => {
state.loading = false
state.error = err
throw err
})
return state
}
export function loadMap (obj) {
const state = {
loading: false,
loaded: {},
error: null
}
const promises = []
try {
Object.keys(obj).forEach(key => {
const result = load(obj[key])
if (!result.loading) {
state.loaded[key] = result.loaded
state.error = result.error
} else {
state.loading = true
}
promises.push(result.promise)
result.promise
.then(res => {
state.loaded[key] = res
})
.catch(err => {
state.error = err
})
})
} catch (err) {
state.error = err
}
state.promise = Promise.all(promises)
.then(res => {
state.loading = false
return res
})
.catch(err => {
state.loading = false
throw err
})
return state
}
function resolve (obj) {
return obj && obj.__esModule ? obj.default : obj
}
export function resolveRender (loaded, props) {
return React.createElement(resolve(loaded), props)
}
export function flushInitializers (initializers) {
const promises = []
while (initializers.length) {
const init = initializers.pop()
promises.push(init())
}
return Promise.all(promises).then(() => {
if (initializers.length) {
return flushInitializers(initializers)
}
})
}