My goal is to run the longRunnigTask
and the quickTask
functions in parallel:
function longRunnigTask() {
return new Promise((resolve) => {
console.log('longRunnigTask started');
for (let i = 0; i < 999999999; i++) {};
console.log('longRunnigTask ended');
resolve();
});
}
function quickTask() {
return new Promise((resolve) => {
console.log('quickTask started');
console.log('quickTask ended');
resolve();
});
}
(function() {
Promise.all([
longRunnigTask(),
quickTask()
]);
})();
My expected output is:
longRunnigTask started
quickTask started
quickTask ended
longRunnigTask ended
But I get:
longRunnigTask started
longRunnigTask ended
quickTask started
quickTask ended
It's possible to achieve this without external libraries or I'm doing something wrong?
In your main long block loop you can do some super tiny pauses like this
const timeout = (ms) => new Promise(resolve => setTimeout(resolve, ms)); function longRunnigTask() { return new Promise(async (resolve) => { console.log('longRunnigTask started'); for (let i = 0; i < 999999999; i++) { if(i === 5555) await timeout(1); }; console.log('longRunnigTask ended'); resolve('res from long'); }); } function quickTask() { return new Promise((resolve) => { console.log('quickTask started'); console.log('quickTask ended'); resolve('res from quick'); }); } (async () => { longRunnigTask().then((res) => console.log(res)); quickTask().then((res) => console.log(res)); })();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.