如何并行运行两个setTimeout任务?

问题描述 投票:0回答:1

我正在阅读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转换为并行运行...对于如何实现此目标,我不太了解:

问题:我们如何更新下面的代码,以便barfoo并行运行,因此输出有两个以上的可能结果?

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);
javascript parallel-processing mutable
1个回答
0
投票

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);
© www.soinside.com 2019 - 2024. All rights reserved.