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! })