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

"Improve text visibility on your website with Google PageSpeed's 'Ensure text remains visible' feature, potentially saving you

Click here for the image reference showing the 0ms potential saving message I'm having trouble with a warning in Google PageSpeed and I've tried everything. This is the code I'm using to define the font-family: @font-face { font-family: ...

Is there a workaround for utilizing reducer dispatch outside of a React component without relying on the store?

Recently, I implemented a reducer in my project that involves using react, typescript and nextJS. I am wondering if there is a method to trigger the reducer outside of a react component, such as from an API service. While searching for solutions, most re ...

Is there a method in Vuejs to choose a tab and update components simultaneously?

Currently facing an issue where selecting a tab does not refresh the input field in another component, causing data persistence. The data is stored in vuex, so I'm looking for a solution to refresh the component for usability. Appreciate any assistanc ...

npm not only loads the packages specified in my package.json file

Currently, I am working on a small project utilizing npm, bower, and grunt. Upon executing "npm install" on my personal computer, it seems to be loading an excessive amount of peculiar items (refer to attached screenshot). However, when performing the same ...

Injecting properties into higher order functions in Typescript allows for the dynamic customization

I'm curious about the process of composing functions that take an object as the sole argument, where each higher order function adds a property. For instance, I have a function that takes a context as input. I would like to wrap this function with a w ...

The display of temporary headers - Nodemailer - AJAX

I keep receiving a warning in the request header that says: Provisional headers are shown. I'm struggling to identify the root cause of this issue. This warning prevents the readyState from changing and my callbacks on the eventhandler onreadystatecha ...

Sequelize associations are not functioning optimally as expected

Trying to display a nested relationship: Cat.hasMany(legs) Leg.belongsTo(cat) Leg.hasOne(paw) paw.hasMany(leg) This is the Cat Model: module.exports = (sequelize, DataTypes) => { const Cat = sequelize.define('Cat', { us ...

What is the easiest way to clear browser cache automatically?

Hello, I have implemented an ajax auto complete function in one of my forms. However, I am facing an issue where over time, the suggestions get stored and the browser's suggestion list appears instead of the ajax auto complete list, making it difficul ...

What is the best way to transfer a property-handling function to a container?

One of the main classes in my codebase is the ParentComponent export class ParentComponent extends React.Component<IParentComponentProps, any> { constructor(props: IParentComponent Props) { super(props); this.state = { shouldResetFoc ...

Is it possible to convert an object with properties of equal length into a list of objects using JavaScript?

I am working with an object that has multiple keys, each containing a list of equal length: myobj = { 'key1' : [1, 2, 3], 'key2' : ['a', 'b', 'c'], 'key3' : [true, false, true], .. ...

Is it possible to have unique color tags in Material UI Autocomplete?

I'm currently diving into the world of material-ui and encountering some challenges that I could use help with. I am trying to incorporate multiple arrays into the autocomplete menu (e.g., options={top100Films, top100Shows}, but with the correct sy ...

Is there a way to eliminate the blue border from a Material React Modal?

I am currently using the React Material Modal and noticed that in the demo examples, there is a blue border when the modal is opened. Is there a way to remove this blue border? I have tried setting the disableAutoFocus property to "true" in the Modal Api ...

Simple integration of JSP, JSON, and AJAX

I need help testing a simple login functionality using AJAX. Here's the code snippet: <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Login Test Page</title> <script src="../js/j ...

Determine whether an input is currently in a "checked" state

I am working with this simple HTML layout: <fieldset> <input/> <label></label> <div class="toggle_box"> <div class="switch"></div> </div> </fieldset> My goal is to achieve the ...

the status of timers across various servers

I have come across a minor architecture issue that I am seeking help to resolve. My website sells products with limited inventory, and when a customer clicks the purchase button, my server updates the database with the details of the potential sale. This i ...

Utilize Typescript Functions to Interact with GeoJSON Data in Palantir Foundry

Working on a map application within Palantir utilizing the workshop module. My goal is to have transport routes showcased along roads depending on user inputs. I am familiar with displaying a route using GeoJSON data, but I'm wondering if there is a w ...

Verify the login details of a distant website using Angular

Currently, I am in the process of developing a user interface for Hacker News using Angular 7. Typically, I rely on public APIs for various functionalities, but unfortunately, login services are not accessible through these APIs. In order to address this ...

The functions getFiles and getFolders will consistently retrieve a single file or folder each time they are

When attempting to fetch all files and folders from my Google Drive, the function .getFiles() is only returning one file, while .getFolders() is only returning a single folder. However, I can confirm that there are multiple folders and files in my drive. ...

unable to make a request to the express server with axios

I am in the process of developing a chat application similar to whatsapp. One of the key features I'm working on is that when a user clicks on another person's name, their chats will be displayed. However, currently, I'm facing an issue wher ...

Dealing with performance issues in React Recharts when rendering a large amount of data

My Recharts use case involves rendering over 20,000 data points, which is causing a blocking render: https://codesandbox.io/s/recharts-render-blocking-2k1eh?file=/src/App.tsx (Check out the CodeSandbox with a small pulse animation to visualize the blocki ...