是否可以从一系列承诺中删除承诺?



我想创建类似的东西,同时处理同步行为和异步行为。 例如,我希望能够这样的事情:

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);
}
}

在这里,我想从午餐承诺中删除返回完成测试的承诺 我已经尝试过:

launchedPromise.splice( lunchedTests.indexOf(finishedTest), 1 );
launchedPromise = lunchedTests.filter(prom => prom !== finishedTest);

它显然不起作用,因为(完成测试!== 承诺午餐[0](它甚至不是同一类型,但我需要测试^^。 我也试图访问PromiseValue,但没有成功。

如果我们只保留由 [*] 标记的控制台.log((。我想得到以下输出:

{ "wait": 10, "nextIndex": 2, "id": 1 }  
{ "wait": 5, "nextIndex": -1, "id": 3 }]
{ "wait": 500, "nextIndex": -1, "id": 2 }

所以,这篇文章的答案是这个函数:

for (let i = 0; i < LaunchedTests.length; i++) {
if (LaunchedTests[i].id === finishedTest.scenario + finishedTest.name) {
return Promise.resolve(LaunchedTests.splice(i, 1));
}
}
return Promise.reject("not find");

但首先你需要像这样初始化一个 id:

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;

您的承诺将具有以下形式:Promise { <pending>, id: YourId },您将能够通过findIndex()函数访问它,您只需splice它。

感谢@dx-over-dt和大家对我的帮助!

最新更新