我通过 MDN 文档找到了以下代码。
var resolveAfter2Seconds = function() {
console.log("starting slow promise");
return new Promise(resolve => {
setTimeout(function() {
resolve(20);
console.log("slow promise is done");
}, 2000);
});
};
var resolveAfter1Second = function() {
console.log("starting fast promise");
return new Promise(resolve => {
setTimeout(function() {
resolve(10);
console.log("fast promise is done");
}, 1000);
});
};
var parallel = function() {
console.log('==PARALLEL with Promise.then==');
resolveAfter2Seconds().then((message)=>console.log(message));
resolveAfter1Second().then((message)=>console.log(message));
}
作为执行的结果,我认为每个 Promise 都将是没有顺序保证的并行执行。
但是我写了下面的代码,似乎可以保证顺序。
const promiseFunction1 = () => {
return new Promise((resolve) => {
let result = 0;
for (let i = 0; i < 1000000000; i++) {
result += 1;
}
resolve(result);
})
}
const promiseFunction2 = () => {
return new Promise((resolve) => {
let result = 0;
for (let i = 0; i < 10; i++) {
result += 1;
}
resolve(result);
})
}
const parallel = () => {
promiseFunction1()
.then(res => console.log(res));
promiseFunction2()
.then(res => console.log(res));
}
这两个代码有什么区别?
附录
下面的两个代码是一样的吗?
1.
const parallel = () => {
promiseFunction1()
.then(res => console.log(res));
promiseFunction2()
.then(res => console.log(res));
}
2.
const parallel = () => {
promiseFunction1()
.then(res1 => {
console.log(res1);
promiseFunction2()
.then(res2 => {
console.log(res2);
})
});
}