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

时间:2019-12-12 16:36:28

标签: javascript node.js promise

我想创建类似的东西来同时处理同步行为和异步行为。 例如,我想要这样的东西:

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中删除返回finishTest的诺言 我已经尝试过的:

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 }

1 个答案:

答案 0 :(得分: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和所有人对我的帮助!