File tree Expand file tree Collapse file tree 3 files changed +65
-2
lines changed Expand file tree Collapse file tree 3 files changed +65
-2
lines changed Original file line number Diff line number Diff line change @@ -198,10 +198,49 @@ eventproxy 这套处理异步并发的思路,我一直觉得就像是汇编里
198
198
199
199
编程语言美丑啥的,咱心中有佛就好。
200
200
201
- 回到正题,之前我们已经得到了一个长度为 40 的数组 ,里面包含了每条主题的链接。那么意味着,我们接下来要发出 40 个并发请求。我们需要用到 eventproxy 的 ` #after ` API。
201
+ 回到正题,之前我们已经得到了一个长度为 40 的 ` topicUrls ` 数组 ,里面包含了每条主题的链接。那么意味着,我们接下来要发出 40 个并发请求。我们需要用到 eventproxy 的 ` #after ` API。
202
202
203
203
大家自行学习一下这个 API 吧:https://github.com/JacksonTian/eventproxy#%E9%87%8D%E5%A4%8D%E5%BC%82%E6%AD%A5%E5%8D%8F%E4%BD%9C
204
204
205
+ 我代码就直接贴了哈。
206
+
207
+ ``` js
208
+ // 得到 topicUrls 之后
209
+
210
+ // 得到一个 eventproxy 的实例
211
+ var ep = new eventproxy ();
212
+
213
+ // 命令 ep 重复监听 topicUrls.length 次(在这里也就是 40 次) `topic_html` 事件再行动
214
+ ep .after (' topic_html' , topicUrls .length , function (topics ) {
215
+ // topics 是个数组,包含了 40 次 ep.emit('topic_html', pair) 中的那 40 个 pair
216
+
217
+ // 开始行动
218
+ topics = topics .map (function (topicPair ) {
219
+ // 接下来都是 jquery 的用法了
220
+ var topicUrl = topicPair[0 ];
221
+ var topicHtml = topicPair[1 ];
222
+ var $ = cheerio .load (topicHtml);
223
+ return ({
224
+ title: $ (' .topic_full_title' ).text ().trim (),
225
+ href: topicUrl,
226
+ comment1: $ (' .reply_content' ).eq (0 ).text ().trim (),
227
+ });
228
+ });
229
+
230
+ console .log (' final:' );
231
+ console .log (topics);
232
+ });
233
+
234
+ topicUrls .forEach (function (topicUrl ) {
235
+ superagent .get (topicUrl)
236
+ .end (function (err , res ) {
237
+ console .log (' fetch ' + topicUrl + ' successful' );
238
+ ep .emit (' topic_html' , [topicUrl, res .text ]);
239
+ });
240
+ });
241
+ ```
242
+
243
+ 完整的代码请查看 lesson4 目录下的 app.js 文件
205
244
206
245
207
246
Original file line number Diff line number Diff line change @@ -18,6 +18,30 @@ superagent.get(cnodeUrl)
18
18
topicUrls . push ( href ) ;
19
19
} ) ;
20
20
21
- console . log ( topicUrls ) ;
21
+ var ep = new eventproxy ( ) ;
22
+
23
+ ep . after ( 'topic_html' , topicUrls . length , function ( topics ) {
24
+ topics = topics . map ( function ( topicPair ) {
25
+ var topicUrl = topicPair [ 0 ] ;
26
+ var topicHtml = topicPair [ 1 ] ;
27
+ var $ = cheerio . load ( topicHtml ) ;
28
+ return ( {
29
+ title : $ ( '.topic_full_title' ) . text ( ) . trim ( ) ,
30
+ href : topicUrl ,
31
+ comment1 : $ ( '.reply_content' ) . eq ( 0 ) . text ( ) . trim ( ) ,
32
+ } ) ;
33
+ } ) ;
34
+
35
+ console . log ( 'final:' ) ;
36
+ console . log ( topics ) ;
37
+ } ) ;
38
+
39
+ topicUrls . forEach ( function ( topicUrl ) {
40
+ superagent . get ( topicUrl )
41
+ . end ( function ( err , res ) {
42
+ console . log ( 'fetch ' + topicUrl + ' successful' ) ;
43
+ ep . emit ( 'topic_html' , [ topicUrl , res . text ] ) ;
44
+ } ) ;
45
+ } ) ;
22
46
} ) ;
23
47
You can’t perform that action at this time.
0 commit comments