File tree Expand file tree Collapse file tree 1 file changed +64
-0
lines changed Expand file tree Collapse file tree 1 file changed +64
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * async的执行原理
3+ * 其实就是自动执行generator函数
4+ * 暂时不考虑genertor的编译步骤(更复杂)
5+ */
6+
7+ const getData = ( ) =>
8+ new Promise ( resolve => setTimeout ( ( ) => resolve ( "data" ) , 1000 ) )
9+
10+ // 这样的一个async函数 应该再1秒后打印data
11+ async function test ( ) {
12+ const data = await getData ( )
13+
14+ console . log ( data )
15+ return data
16+ }
17+
18+ // async函数会被编译成generator函数 (babel会编译成更本质的形态,这里我们直接用generator)
19+ function * testG ( ) {
20+ // await被编译成了yield
21+ const data = yield getData ( )
22+ console . log ( 'data: ' , data ) ;
23+ const data2 = yield getData ( )
24+ console . log ( 'data2: ' , data2 ) ;
25+ return data + '123'
26+ }
27+
28+ function asyncToGenerator ( generatorFunc ) {
29+ return function ( ) {
30+ const gen = generatorFunc . apply ( this , arguments )
31+
32+ return new Promise ( ( resolve , reject ) => {
33+ function step ( key , arg ) {
34+ let generatorResult
35+ try {
36+ generatorResult = gen [ key ] ( arg )
37+ } catch ( error ) {
38+ return reject ( error )
39+ }
40+
41+ const { value, done } = generatorResult
42+
43+ if ( done ) {
44+ return resolve ( value )
45+ } else {
46+ return Promise . resolve ( value ) . then (
47+ function onResolve ( val ) {
48+ step ( "next" , val )
49+ } ,
50+ function onReject ( err ) {
51+ step ( "throw" , err )
52+ } ,
53+ )
54+ }
55+ }
56+ step ( "next" )
57+ } )
58+ }
59+ }
60+
61+ const testGAsync = asyncToGenerator ( testG )
62+ testGAsync ( ) . then ( result => {
63+ console . log ( result )
64+ } )
You can’t perform that action at this time.
0 commit comments