严格来说,由于JavaScript是单线程,所以没有并发。有类似并发操作的,那就是协程。ES6中有async和await,用它们来实现异步操作,简直很爽。但是,并不是用了async就可以并发,或者接近并发了。一般有两种方式可以让他们“并发”。
有趣的是,Python 3.5以后也有了async
和await
这两个关键字的协程操作了。真的是天下语言一大抄!喂,Ruby,你睡着了么?
//方法1
let results = await Promise.all([testPromise(), testPromise()])
//方法2
let p1 = testPromise();
let p2 = testPromise();
let r1 = await p1;
let r2 = await p2;
下面是一个例子,源于MDN,自己加上了Promise.all
。前一个测试同步操作,即9秒后打印结果。后两个会并发操作,即3秒打印结果。
function timeoutPromise(interval) {
return new Promise((resolve, reject) => {
setTimeout(function(){
resolve("done");
}, interval);
});
};
async function slowTimeTest() {
await timeoutPromise(3000);
await timeoutPromise(3000);
await timeoutPromise(3000);
}
let startTime = Date.now();
slowTimeTest().then(() => {
let finishTime = Date.now();
let timeTaken = finishTime - startTime;
console.log("slowTimeTest finished in milliseconds: " + timeTaken);
})
async function fastTimeTest1() {
const timeoutPromise1 = timeoutPromise(3000);
const timeoutPromise2 = timeoutPromise(3000);
const timeoutPromise3 = timeoutPromise(3000);
await timeoutPromise1;
await timeoutPromise2;
await timeoutPromise3;
}
startTime = Date.now();
fastTimeTest1().then(() => {
let finishTime = Date.now();
let timeTaken = finishTime - startTime;
console.log("fastTimeTest1 finished in milliseconds: " + timeTaken);
})
async function fastTimeTest2() {
let res = await Promise.all([timeoutPromise(3000), timeoutPromise(3000), timeoutPromise(3000)]);
console.log('Data', res);
}
startTime = Date.now();
fastTimeTest2().then(() => {
let finishTime = Date.now();
let timeTaken = finishTime - startTime;
console.log("fastTimeTest2 finished in milliseconds: " + timeTaken);
})