Home > Software engineering >  Angular subscription to switchMap() function does not wait for setInterval() and returns undefined
Angular subscription to switchMap() function does not wait for setInterval() and returns undefined

Time:11-05

This is the function which subscribes to the switchmap

  mintNft(): void {

    this.__mmservice.mintNft().subscribe({
      next: (response: any) => {
        console.log(response, 'next response')
      },
      error: (response: any) => {
        console.log(response, 'error response')
      },
      complete: () => {
        console.log('123')
      },
    });

  }

This is the switchmap function which returns undefined.

      switchMap(

        async (response) => {
          console.log("Transaction sent!", response);

          const interval = setInterval(function () {
            console.log("Attempting to get transaction receipt...");
            window.web3.eth.getTransactionReceipt(response, function (err, rec) {
              if (rec) {
                if (rec.status) {
                  console.log('success') 
                }
                clearInterval(interval);
                return rec.result.status
              }
            });
          }, 1000);
        })

I want subscription to wait and return rec.result.status which becomes true after some seconds

rec.result.status 

CodePudding user response:

Your switchMap isn't returning a promise nor an Observable.

You could do like following :

switchMap(
    async (response) => {
        return new Promise((resolve) => {
            console.log("Transaction sent!", response);
            const interval = setInterval(function () {
                console.log("Attempting to get transaction receipt...");
                window.web3.eth.getTransactionReceipt(response, function (err, rec) {
                    if (rec) {
                        if (rec.status) {
                            console.log('success')
                        }
                        clearInterval(interval);
                        resolve(rec.result.status);
                    }
                });
            }, 1000);
        })
    }
)
  • Related