按顺序执行数组中的承诺 socket.io

Execute promises in an array sequentially socket.io

我有一个简单的函数 createRun(),其中 returns 是一个 Promise。承诺评估为一个对象。函数内的代码并不真正相关。我有另一个名为 createGroupRun() 的函数,它基本上循环遍历数组 (testIds) 并调用创建 运行 函数。现在,当 createRun() 函数完成后,我想发出这个:

io.emit('group run created', {run, testId});

我有这个createGroupRun():


export async function createGroupRun(projectId: string, testIds: string[], runIds: string[], reqUrl: string) {
    try {
        const groupRunId = uuid();

        const projectPath = path.resolve(__dirname, `../../projects/${projectId}`);

        await mkdir(`${projectPath}/group-${groupRunId}`);

        const runPromises = testIds.map(async (testId) => createRun(projectId, testId, reqUrl));

        return group;
    } catch (error) {
        console.log(error);

        return error;
    }
}

runPromises 包含调用 createRun() 函数的结果。我想遍历它,执行 createRun 函数,发出上面显示的事件,移动到下一个元素,执行 createRun 函数,发出事件...冲洗并重复。

如何做到这一点?关于这个有很多问题但是 none 和 socket.io

如果您想 运行 在循环中使用 async/await 异步代码,串联而不是并行 - 使用 for 循环

export async function createGroupRun(projectId: string, testIds: string[], runIds: string[], reqUrl: string) {
    try {
        const groupRunId = uuid();
        const projectPath = path.resolve(__dirname, `../../projects/${projectId}`);
        await mkdir(`${projectPath}/group-${groupRunId}`);
        for (let testId of testIds) {
            await createRun(projectId, testId, reqUrl);
        }
        return group;
    } catch (error) {
        console.log(error);
        return error;
    }
}