Marlon's Blog

记录生活、技术中的二三事.


  • Home

  • Archives

  • Tags

  • Bio

javascript异步理解

Published at: 2015-08-13   |   Reading: 153 words ~1min

废话不说,直接扔代码

 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
interface TaskFunction {
	(done: (result?: any) => void): void;
}

function all(taskFns: TaskFunction[], callback: (results: any[]) => void): void {
	var results: string[] = [];

	var pending = taskFns.length;

	taskFns.forEach((taskFn, index) => {
		taskFn(result => {
			if (index in results) {
				return;
			}

			results[index] = result;

			if (--pending == 0) {
				callback(results);
			}
		});
	});
}

all([
	done => {
		done('hello');
	},
	done => {
		setTimeout(() => {
			done(', ');
		}, 100);
	},
	done => {
		setInterval(() => {
			done('world');
		}, 1000);
	},
	done => {
		done('!');
	}
], results => {
	console.log(results.join('')); // 输出 hello, world!
})
#javascript#
  • Author: Marlon Fan
  • Link: https://www.marlon.life/2015/08/13/about-javascript-async/
  • License: All articles in this blog are licensed under CC BY-NC-ND 4.0 unless stating additionally.
Express中间件加载
virtualbox报R3相关错误
Marlon Fan

Marlon Fan

宁静致远

48 Blogs
30 Tags
Homepage GitHub Twitter Zhihu
Friends
    过往云烟
© 2008 - 2024 Marlon Fan. All rights reserved. 晋ICP备20002733号-1
0%