Home > OS >  Exiting method before finishing if statement
Exiting method before finishing if statement

Time:12-27

I have a simple function that calls a method of a lib I'm implementing, and during the execution I have a if statement.

The problem is that my function is ending before exiting the if statement, there's a way to make my function wait the resolution of the if?

Here's my code:

public getHistory(): any {
  console.log('ENTER FUNC');
  this.channel.history((err: ErrorEvent, resultPage: any) => {
    if (err) {
      console.log(err.message);
    } else {
      this.messages = resultPage.items;
      console.log('EXIT IF');
    }
  });
  console.log('EXIT FUNCTION');
  return this.messages;
}

And the output: Output image

I tryed to make a async function and put the await on the call of the lib's method expecting the function to wait the return of the method to them finish, the function ended before finishing the if

CodePudding user response:

If the history function does not return a promise (promise is the object you use async / await on), you can create a promise and resolve it inside the history function.

try {
  const result = await new Promise((resolve, reject) => {
    this.channel.history((err: ErrorEvent, resultPage: any) => {
      if (err) {
        reject(err);
      } else {
        resolve(resultPage);
      }
    });
  });

  this.messages = result.items;
  console.log('EXIT IF');
} catch (err) {
  console.log(err.message);
}
  • Related