How to "wait" for a sync method to complete

I am making a context menu, and in this menu, I am using a key for translation.
I would like to "wait" for this method to finish, before moving on, and display the context menu on my page only when I am certain, that the translation files have already been loaded.

So, here is what I have tried.

contextMenuContent: {
  [key: string]: ContextMenuEntries;
};

constructor(private translationService: TranslationService) {
}

async ngOnInit() {
  this.contextMenuContent = await this.makeContextMenuEntries();
}

async makeContextMenuEntries() {
  return {
    editContextMenuEntry: {
      icon: 'edit',
      text: this.t('edit_contacts'),
      action: () => {}
    }
  };
}

t<T = string>(key: string, param?: object): T {
  return this.translationService.translate(`${TRANSLATION_KEY}.${key}`, param);
}

It is working, but I am looking for a better solution, and I really want to avoid marking ngOnInit as async. How can I improve my code?

>Solution :

By default, angular will wait for all the SYNC functions in ngOnInit to finish.

You can do a quick demonstration by running:

ngOnInit(){
    let a = '';
    for (let i = 0; i < 10000000; i++) {
      a += i.toString();
    }
}

You will see that the component will be displayed only after a few seconds, the time for the functions in ngOnInit to finish.

So in your case, if the translation doesn’t exist, there aren’t too many solutions:

  • Display nothing because the translation service will never get the solution. No async and await are required because all are SYNC.

    ngOnInit() {
        this.contextMenuContent = this.makeContextMenuEntries();
    }
    
      makeContextMenuEntries() {
       return {
         editContextMenuEntry: {
           icon: 'edit',
           text: this.t('edit_contacts'),
           action: () => {}
         }
       };
    }
    
    t<T = string>(key: string, param?: object): T {
       return this.translationService.translate(`${TRANSLATION_KEY}.${key}`, param);
    }
    
  • Change your translate method for a promise so it would wait the translation in an async way.

Leave a Reply