I want to create somthing like that handle synchronous behavior and asynchronous behavior at the same time. For example I would like to be able something like that :
function timeout(myJson) {
return new Promise(function (resolve, reject) {
setTimeout(resolve, myJson.wait, myJson);
});
}
async function funct() {
try {
let PromiseTolaunch = [{ "wait": 10, "nextIndex": 2, "id": 1 },
{ "wait": 500, "nextIndex": -1, "id": 2 },
{ "wait": 5, "nextIndex": -1, "id": 3 }];
let launchedPromise = [], finishedPromise;
launchedPromise.push(timeout(PromiseTolaunch[0]));
launchedPromise[0].id = PromiseTolaunch[0].id;
launchedPromise.push(timeout(PromiseTolaunch[1]));
launchedPromise[1].id = PromiseTolaunch[1].id;
while (launchedPromise.length !== 0) {
finishedPromise = await Promise.race(launchedPromise);
[*] console.log(finishedPromise); // Expected output: { "wait": 10, "nextIndex": 2 }
//console.log(launchedPromise); // Expected output : [Promise { { wait: 10, nextIndex: 2, id: 1 }, id: 1 }, Promise { <pending>, id: 2 } ]
//I want to :
//Remove the promise that just been executed from launchedPromise
//console.log(launchedPromise); // Expected output : [ Promise { <pending>, id: 2 } ]
if (finishedPromise.nextIndex !== -1) {
launchedPromise.push(timeout(PromiseTolaunch[finishedPromise.nextIndex]));
}
}
return Promise.resolve("done")
} catch (error) {
return Promise.reject(error);
}
}
Here i want to remove the promise that returned finishedTest from lunchedPromise What I already tried :
launchedPromise.splice( lunchedTests.indexOf(finishedTest), 1 );
launchedPromise = lunchedTests.filter(prom => prom !== finishedTest);
And it obviously does not work because (finishedTest !== PromiseToLunch[0]) It is not even the same type but I needed to test ^^. I also tried to access to PromiseValue without sucess.
If we conserve only the console.log() that is mark by a [*]. I would like to get the following output :
{ "wait": 10, "nextIndex": 2, "id": 1 }
{ "wait": 5, "nextIndex": -1, "id": 3 }]
{ "wait": 500, "nextIndex": -1, "id": 2 }