【问题标题】:TypeScript - wait for the function to complete until executing the next functionTypeScript - 等待函数完成,直到执行下一个函数
【发布时间】:2022-01-02 06:44:29
【问题描述】:

我有两个函数:doAsyncStuff 和 doNextStep。 如何确保 doNextStep 仅在 doAsyncStuff 完成后执行?

我尝试了类似的方法,但没有帮助:doAsyncStuff().then(_ => doNextStep());

async function doAsyncStuff() {
    if (vscode.workspace.workspaceFolders) {
        vscode.workspace.workspaceFolders.forEach(async (e) => {
            for (const [name, type] of await vscode.workspace.fs.readDirectory(e.uri)) {
                console.log(name);
            }
        });
    
    }
    return true;
}

function doNextStep() {
    console.log('next step');
}

【问题讨论】:

  • 你在哪里执行doNextStep
  • 您应该使用实际的foreach 而不是函数。回调调用者不等待回调函数。
  • 在这里使用forEach 将不允许在该函数返回之前解决promise。您应该将其替换为map,并将结果包装在Promise.all 中,您可以使用await 确保在执行下一步之前所有这些都完成。
  • await Promise.all(vscode.workspace.workspaceFolders.map(async ... await)) 可以解决问题。

标签: typescript async-await


【解决方案1】:

非常感谢您的回复,hotcakedev 的解决方案开箱即用。 Promise.all(vscode.workspace.workspaceFolders.map(async ... await))

这就是它的样子(结果场景使用异步递归函数'readFolders',它也运行良好):

        await Promise.all(vscode.workspace.workspaceFolders.map(async x => {


            for (const [name, type] of await vscode.workspace.fs.readDirectory(x.uri)) {
               console.log(name);
            }
            // await readFolders(x.uri,x.uri.path);



        }));



        console.log('fin');

【讨论】:

  • 很高兴有帮助!
猜你喜欢
  • 2019-02-16
  • 1970-01-01
  • 1970-01-01
  • 2015-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多