Javascript异步理解
Opened this issue · 1 comments
marlonfan commented
直接扔代码
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!
})
marlonfan commented
整理代码的时候发现自己当时好搓... 当初把这团代码扔上来的目的到底是什么呢. 我擦,好好想想...
现在看看起来,觉得js的异步应该是属于两个东西在同时运行. 一个负责同步,而另外一个负责异步操作. 而我们一般用的都是同步的这个,异步的则交由另外一个去执行. 所以在同步的这个线程是拿不到异步的结果的.