Замена операторов затем на try / catch - PullRequest
0 голосов
/ 20 марта 2020

Я пытаюсь удалить операторы then из следующего фрагмента кода, а затем заменить все перехваты операторами try / catch. У меня есть некоторые проблемы, зная, что делать с тогдашними утверждениями.

    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) {
...

1 Ответ

0 голосов
/ 20 марта 2020

Похоже, вы на правильном пути со вторым блоком кода. then вызывается для обещания, поэтому вместо использования 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)
}

Сложность в вашем примере заключается в том, что код находится в конструкторе класса, и эти не могут быть асинхронными c.

...