1. js 异步的几种情况 :
1.1 异步操作由浏览器内核的 webcore 来执行:
onclick 由浏览器内核的 DOM Binding 模块来处理,当事件触发的时候,回调函数会立即添加到任务队列中。
setTimeout 会由浏览器内核的 timer 模块来进行延时处理,当时间到达的时候,才会将回调函数添加到任务队列中。
ajax 则会由浏览器内核的 network 模块来处理,在网络请求完成返回之后,才将回调添加到任务队列中。
1.2 如:http (ajax)、UI 重绘 、事件 ( onclick )、延时函数 (setTimeout)
2. 异步函数返回值处理
2.1 setTimeout
function getSomething(cb) { var r = 0; setTimeout(function () { r = 2; cb(r); }, 2000); } function compute(x) { console.log(x); } getSomething(compute);
2.2 promise
function getSomething() { var r = 0; return new Promise(function(resolve) { setTimeout(function(){ r = 2; resolve(r); },2000) }) } function compute(x) { console.log(x * 2); } getSomething().then(compute);
2.3 async
function getSomething() { var r = 0; return new Promise(function(resolve) { setTimeout(function() { r = 2; resolve(r); },2000) }) } async function compute() { var x = await getSomething(); console.log(x * 2); } compute();
2.4 generator
function getSomething() { var r = 0; setTimeout(function() { r = 2; it.next(r); },2000); } function *compute(it) { var x = yield getSomething(); console.log(x * 2); } var it = compute(); it.next();
2.5 promise和generator相结合
function getSomething() { var r = 0; return new Promise(function(resolve) { setTimeout(function() { r = 2; resolve(r); },2000) }) } function *compute() { var x = yield getSomething(); console.log(x * 2); } var it = compute(); it.next().value.then(function(value) { it.next(value); })
3. 相关文章