我正在阅读YDKJS,并且我们在早期谈论的是异步,并行和并发代码之间的区别。
我有一个简单的异步示例:
let output = 0;
const bar = (cb) => setTimeout(cb, Math.random() * 1000);
const foo = (cb) => setTimeout(cb, Math.random() * 1000);
bar( () => {
output = 1;
});
foo( () => {
output = 2
});
setTimeout(() => {
// This Async code should have 2 different outputs
output;
}, 2000);
以上代码可以基于Math.random计时器和可变输出获得2个答案:
但是,我想增加一点复杂度,并将foo和bar转换为并行运行...对于如何实现此目标,我不太了解:
问题:我们如何更新下面的代码,以便bar
和foo
并行运行,因此输出有两个以上的可能结果?
let output = 0;
let inputA = 10;
let inputB = 11;
const bar = (cb) => setTimeout(cb, Math.random() * 1000);
const foo = (cb) => setTimeout(cb, Math.random() * 1000);
bar( () => {
inputA++;
inputB = inputA;
output = inputA + 1;
});
foo( () => {
inputB--;
inputA = inputB;
output = inputB * 2;
});
setTimeout(() => {
// This Parallel code should have more than 2 outputs;
output;
}, 2000);
let output = 0;
let inputA = 10;
let inputB = 11;
const bar = (cb) => setTimeout(cb, Math.random() * 1000);
const foo = (cb) => setTimeout(cb, Math.random() * 1000);
bar( () => {
inputA++;
inputB = inputA;
output = inputA + 1;
});
foo( () => {
inputB--;
inputA = inputB;
output = inputB * 2;
});
setTimeout(() => {
Promise.all([bar(),foo()])
.then(output => console.log(output));
}, 2000);