【发布时间】:2017-07-23 08:33:04
【问题描述】:
大约一个月前刚刚完成的 ECMAScript-2017 引入了 'asynchronous functions' 作为新功能。为了了解它们的“异步”程度,我在 Chrome 中进行了测试:
async function af1(){
for (let i=0; i<300; i++)
await (new Promise(
(resolve,reject)=>{
for (let j=0; j<=4; j++) console.log(j);resolve();}))
.then(()=>{for (let j=100; j<=400; j+=100) console.log(j);});;
}
async function af2(){
for (let i=0; i<300; i++)
await (new Promise(
(resolve,reject)=>{
for (let j=5; j<=9; j++) console.log(j);resolve();}))
.then(()=>{for (let j=500; j<=900; j+=100) console.log(j);});
}
af1();
console.log(300);
af2();
console.log(400);
// 0 1 2 3 4 300 5 6 7 8 9 400 100 200 300 400 500 600 700 800 900
// 0 1 2 3 4 5 6 7 8 9 100 200 300 400 500 600 700 800 900
// 0 1 2 3 4 5 6 7 8 9 100 200 300 400 500 600 700 800 900
// 0 1 2 3 4 5 6 7 8 9 100 200 300 400 500 600 700 800 900
// 0 1 2 3 4 5 6 7 8 9 100 200 300 400 500 600 700 800 900
// 0 1 2 3 4 5 6 7 8 9 100 200 300 400 500 600 700 800 900
// ......
其实我期待一个更随机的序列。
现在,我可以有把握地说,代表 promise 或其中一个 then() 回调的每个代码块都是原子的,因为块内代码的执行不会被同一个程序?
【问题讨论】:
-
“异步”与“多线程”或“并行”没有任何关系。它始终是一个线程,并且所有同步代码块都以独占方式执行,直到它们完成。
标签: javascript asynchronous concurrency async-await