Search code examples
angularweb3js

proeceed the execution once a function has returned in Angular 4


I have a function which uses web3.js to create a new account and return the account address. Here is my service

@Injectable()
export class ContractsService {
  private web3: any;
  public acc_no: any;

  public createAccount(): any {
      this.web3.personal.newAccount('abc123', function (error, result) {
      console.log("in funct");
       if (!error) {
         this.acc_no = result;
       } else {
         this.acc_no = 0;
       }
     }
   );
  }

}

I want to call this function createAccount and once that function has done creating a new account I want my component to proceed the execution. Here is my component;s function calling this createAccount function.

registerUser() {
    if (this.signupData.username !== '' && this.signupData.password !== '' && this.signupData.firstname !== ''
      && this.signupData.lastname !== '') {
        this.contractService.createAccount();
        setTimeout(() => {
          console.log(this.contractService);
          }, 2000);
    }
  }

I have tried using timeout but no luck, I am getting undefined for it. Any thought?

UPDATE

I used promise in following way

public createAccount(): Promise<any> {
       this.web3.personal.newAccount('abc123',  (error, result) => {
      console.log("in funct");
       if (!error) {
           this.acc_no = result;
       } else {
           this.acc_no = 0;
       }
     }
   ).toPromise()
        .then(() => {
          return this.acc_no;
        });
  }

but i am getting this error enter image description here


Solution

  • Try that

     public createAccount(): Promise <number>
     {
    
     return new Promise((resolve, reject) => {
          this.web3.personal.newAccount('abc123',  (error, result) => {
          console.log("in funct");
           if (!error) {
             this.acc_no = result;
             resolve(result);
           } else {
             this.acc_no = 0;
             resolve(result);
             //OR reject();
           }
         }
       );
      }
    }
    
    registerUser()
    {
       //...
        this.contractService.createAccount().then(acc_no => 
        {
           console.log(acc_no);
        });
    }