gpt4 book ai didi

javascript - 可以从一系列 promise 中删除 promise 吗?

转载 作者:行者123 更新时间:2023-12-04 15:38:24 24 4
gpt4 key购买 nike

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

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

在这里,我想删除从 lunchedPromise 返回finishedTest 的 promise
我已经尝试过的:
launchedPromise.splice( lunchedTests.indexOf(finishedTest), 1 );
launchedPromise = lunchedTests.filter(prom => prom !== finishedTest);

它显然不起作用,因为 (finishedTest !== PromiseToLunch[0]) 它甚至不是同一类型,但我需要测试 ^^。
我也尝试在没有成功的情况下访问 PromiseValue。

如果我们只保留由 [*] 标记的 console.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 将采用以下形式: Promise { <pending>, id: YourId }您可以通过 findIndex() 访问它功能,你只需要 splice它。

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

关于javascript - 可以从一系列 promise 中删除 promise 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59309078/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com