【问题标题】:Replacing then statements with try/catch用 try/catch 替换 then 语句
【发布时间】:2020-03-19 22:22:44
【问题描述】:

我正在尝试从以下代码中删除 then 语句,然后用 try/catch 语句替换所有捕获。我在知道如何处理 then 语句时遇到一些问题。

    export class WelcomePageContribution implements IWorkbenchContribution {

    constructor(
        @IInstantiationService instantiationService: IInstantiationService,
        @IConfigurationService configurationService: IConfigurationService,
        @IEditorService editorService: IEditorService,
        @IBackupFileService backupFileService: IBackupFileService,
        @IFileService fileService: IFileService,
        @IWorkspaceContextService contextService: IWorkspaceContextService,
        @ILifecycleService lifecycleService: ILifecycleService,
        @ICommandService private readonly commandService: ICommandService,
    ) {
        const enabled = isWelcomePageEnabled(configurationService, contextService);
        if (enabled && lifecycleService.startupKind !== StartupKind.ReloadedWindow) {
            backupFileService.hasBackups().then(hasBackups => {
                const activeEditor = editorService.activeEditor;
                if (!activeEditor && !hasBackups) {
                    const openWithReadme = configurationService.getValue(configurationKey) === 'readme';
                    if (openWithReadme) {
                        return Promise.all(contextService.getWorkspace().folders.map(folder => {
                            const folderUri = folder.uri;
                            return fileService.resolve(folderUri)
                                .then(folder => {
                                    const files = folder.children ? folder.children.map(child => child.name) : [];

                                    const file = arrays.find(files.sort(), file => strings.startsWith(file.toLowerCase(), 'readme'));
                                    if (file) {
                                        return joinPath(folderUri, file);
                                    }
                                    return undefined;
                                }, onUnexpectedError);
                        })).then(arrays.coalesce)
                            .then<any>(readmes => {
                                if (!editorService.activeEditor) {
                                    if (readmes.length) {
                                        const isMarkDown = (readme: URI) => strings.endsWith(readme.path.toLowerCase(), '.md');
                                        return Promise.all([
                                            this.commandService.executeCommand('markdown.showPreview', null, readmes.filter(isMarkDown), { locked: true }),
                                            editorService.openEditors(readmes.filter(readme => !isMarkDown(readme))
                                                .map(readme => ({ resource: readme }))),
                                        ]);
                                    } else {
                                        return instantiationService.createInstance(WelcomePage).openEditor();
                                    }
                                }
                                return undefined;
                            });
                    } else {
                        return instantiationService.createInstance(WelcomePage).openEditor();
                    }
                }
                return undefined;
            }).then(undefined, onUnexpectedError);
        }
    }
}

让整个事情看起来更像这样..

const enabled = await isWelcomePageEnabled(configurationService, contextService);
if (enabled && lifecycleService.startupKind !== StartupKind.ReloadedWindow) {
const hasBackups = await backupFileService.hasBackups();
const activeEditor = editorService.activeEditor;
if (!activeEditor && !hasBackups) {
    const openWithReadme = configurationService.getValue(configurationKey) === 'readme';
  if (openWithReadme) {
...

【问题讨论】:

    标签: javascript typescript asynchronous try-catch


    【解决方案1】:

    您的第二个代码块似乎走在了正确的轨道上。 then 是在 Promise 上调用的,因此您可以等待函数 then 被调用,而不是使用 then,将其保存到变量中,然后将回调中的代码移动到 then 下方await 在同一缩进级别。每当您 await 时,您都可以将其包装在 try/catch 中,并将本来应该在 catch 回调中的内容放在 catch 块内。

    例如

    fetchData().then(data => {
      console.log(data)
    }).catch(err => {
      console.error(err)
    })
    

    变成

    try {
      const data = await fetchData()
      console.log(data)
    } 
    catch (err) {
      console.error(err)
    }
    

    您的示例中的复杂之处在于代码位于类构造函数中,而那些can't be async

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多