首页 > 解决方案 > 用 try/catch 替换 then 语句

问题描述

我正在尝试从以下代码中删除 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) {
...

标签: javascripttypescriptasynchronoustry-catch

解决方案


It looks like you're on the right track with your second code block. then is called on a promise, so instead of using then you would await the function then was called on, save it to a variable, and then move the code that was in the callback to then below the await at the same indentation level. Whenever you await, you can wrap it in a try/catch and put what would have been in the catch callback inside of the catch block.

So for example

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

becomes

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

The complication in your example is that the code is in a class constructor, and those can't be async.


推荐阅读