Using Angular's async, you can retrieve a value returned by a promise

Within the library I am currently utilizing, there is a method called getToken which can be seen in the following example:

getApplicationToken() {
    window.FirebasePlugin.getToken(function(token) {
      console.log('Received FCM token: ' + token);
    }, function(error) {
      console.log('Failed to retrieve FCM token', error);
    });
  }

My goal is to create a method that directly returns the token itself. Here is what I have attempted:

async getApplicationTokenString(): Promise<string> {
    return window.FirebasePlugin.getToken();
}

I then call this method using:

let firebaseToken = '';
this.fireBaseService.getApplicationTokenString().then(function(resolveOutput) {
   firebaseToken = resolveOutput;
  }, function(rejectOutput) {
    console.log(rejectOutput);
  });

Unfortunately, I only receive an output of Firebase token:, without any actual value. However, when I use getApplicationToken, the FCM token is successfully logged.

How can I properly handle and pass the value obtained from an asynchronous promise?

Answer №1

Enclose the code within a Promise and trigger the resolver when the token becomes accessible

 fetchApplicationToken() {
        return new Promise((resolve, reject) => {
            window.FirebasePlugin.getToken(function(token) {
                console.log('Received FCM token: ' + token);
                resolve(token);
            }, function(error) {
            console.log('Failed to retrieve FCM token', error);
            });
        });
      }

Insert an await operator to pause execution until a Promise is fulfilled

 async processApplicationTokenString(): Promise<string> {
    let token =  await this.fetchApplicationToken();
    console.log(token); // your token will be accessible at this point
    this.firebaseToken = token;
    console.log('This line won't execute until the promise is resolved');
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The NgSwitch is behaving unexpectedly, throwing an exception with the message "No provider for NgSwitch"

My HTML code snippet is shown below: <ng-container *ngIf="col.data !== ''"> <ng-template [ngSwitch]="col.data"> <ng-container *ngSwitchCase="'Page'"> <div>{{g ...

What is causing the loss of data when attempting to access an array field within an object?

So I've been grappling with this issue. I have a collection of objects, each containing string arrays and a string based on the following interface: export interface Subscription { uid: string; books: Array<string>; } The problem arises whe ...

Is there a way to see the default reactions in a browser when keyboard events such as 'tab' keydown occur?

Whenever I press the 'tab' key, the browser switches focus to a different element. I would like to be able to customize the order of focused elements or skip over certain elements when tabbing through a page. While I am aware that I can use preve ...

Unit Testing Angular Components with Karma and Jasmine: Exploring Test Scope

After reading various guides on unit testing, I have gained an understanding that in unit testing, the focus is on testing the logic within a component, with children components tested separately. Despite this knowledge, I still find myself uncertain about ...

How can the outcome of the useQuery be integrated with the defaultValues in the useForm function?

Hey there amazing developers! I need some help with a query. When using useQuery, the imported values can be undefined which makes it tricky to apply them as defaultValues. Does anyone have a good solution for this? Maybe something like this would work. ...

``I'm having trouble getting the onchange event to function properly in a customized

After following a tutorial, I successfully created a custom select dropdown using the provided link. https://www.w3schools.com/howto/tryit.asp?filename=tryhow_custom_select However, I am facing an issue with the onchange event not working for the select ...

There is an issue with the function of elem.autocomplete - it is not recognized

I'm new to Angular.JS and have been struggling for the past 6 hours. I've been working on reading data from an HTTP source and displaying it as an autocomplete feature on the view. Previously, the data was displayed in a select box, but I decide ...

Create a custom Android home screen widget using JavaScript or another programming language

I have a project in mind to create an Android App and include a home-screen widget. While I know it can be done with Native Android, my preference is to use JavaScript for development. Would anyone happen to know of any other solutions that allow the use ...

The process of deleting lines from an image using Javascript

If I have an image of a data-table and I want to eliminate all the grid lines (defined as continuous vertical or horizontal pixels), is there a way to achieve this using Javascript's image data manipulation? I envision looping through a 2D array conta ...

Does it make sense to start incorporating signals in Angular?

The upcoming release, as outlined in RFC3, will introduce signal-based components with change detection strategy solely based on signals. Given the current zone-based change detection strategy, is there any advantage to using signals instead of the tradi ...

A guide to eliminating duplicate values within an array and across multiple arrays with the help of jQuery

Looking for assistance with jQuery to find and alert repeated values in my code. Below are example arrays: a1 = {1,2,3,4,5,6,4} a2= {9,8,7}, a3= {a,b,c,d,e,7} I want to identify the value 4 in array "a1" and give an alert, as well as identify the value ...

OpenAPI implementation in NestJS that emphasizes the use of reusable parameters

Is it possible to reuse common parameters in the implementation of NestJS OpenAPI/Swagger? This feature would prevent me from having to clutter my endpoint with repetitive @ApiImplicitQuery decorators. ...

Utilizing JSON in a d3.js application within a Rails environment

I have been exploring the gem gon in order to generate JSON data from my Rails database. I have successfully managed to display this data in an alert, but now I am looking to visualize it using d3.js. Within my database named "users" with columns (name:st ...

Is it possible to automatically correct all import statements in a TypeScript project?

After transferring some class member variables to a separate class in another file, I realized that these variables were extensively used in the project. As a result, approximately 1000 .ts files will need their imports modified to point to the new class/f ...

Tips for transforming an array of images (from an input field) into a JSON string

After creating an array of images using var a = Array.from(document.getElementById("id").files); I tried to generate a JSON string of that array using var b = JSON.stringify(a); However, all I get is an empty array. It seems like this issue is common w ...

Having trouble displaying a set of data points in a React component

Exploring React, I have built a test app and performed an API call to fetch a large JSON object. After breaking it down into 10 arrays with 3 props each, I am now facing a challenge in sending this data to another component. Despite being able to log the ...

How can I manage the asynchronicity of Hapi.js, fs.readFile, fs.writeFile, and childProcess.exec?

My code execution seems to be resulting in an empty list, could it be that my asynchronous calls are incorrect? I've tried rearranging and breaking things into functions but there still seems to be a timing issue with my execution. The order in which ...

RTK update mutation: updating data efficiently without the need to refresh the page

I am facing an issue with my mui rating component in a post-rating scenario. Although the rating updates successfully in the data, the page does not refresh after a click event, and hence, the rating remains enabled. To address this, I have implemented a d ...

Stopping autoplay in Swiper as soon as you hover over it

My swiper is set to autoplay, but I want it to stop immediately when hovered over instead of waiting for the transition to finish. Is there a way to interrupt the transition and stop it at the exact point where the cursor hovers? Here is my Swiper config ...

Displaying an interactive 2D floorplan in a web browser with the use of html5 and javascript

In the process of updating my old Flash viewer, I am looking to display interactive 2D floorplans exported from AutoCAD. Currently, I convert the AutoCAD files into XML files containing the X and Y coordinates of the various elements on the floorplan such ...