Angular's `await` feature does not wait for the function to complete its execution

Trying to call an async function from a Cordova plugin, but the await keyword doesn't seem to be working:

export class MationLiteService implements IgatewayService {
  async getGroupAllInfo(gatewayId: string, account: string, decryptedpasswd: string) {

// some codes
        return await cordova.plugins.MationPlugin.getGroupAllInfo(data, async (response) => {

        const json: JSON = JSON.parse(response);
        console.log('responseaaaaa:' + response);
        return json;
      }, (error) => {
        console.log('error: ' + error);

      });
  }
}

This is the gateway manager class:

export class GatewayManagerService {
 public  getGroupAllInfo(gatewayType: string, gatewayId: string, account: string, decryptedpasswd: string) {
    return this.gatewayFactoryService.getGateway(gatewayType).getGroupAllInfo(gatewayId, account, decryptedpasswd);
  }
}

Here's how I'm calling it:

  async getAllInfo2(){
     this.facadaService.GetGatewayManagerService().getGroupAllInfo('mation-lite', this.zifan, 'admin', '5555').then((response) => {
        console.log(response);
     });
    //await this.facadaService.GetGatewayManagerService().test('mation-lite');

  }

When trying to print the response, it returns undefined.

Answer №1

await is designed to work with promises, but it seems that MationPlugin.getGroupAllInfo uses a callback function instead of a promise for handling its asynchronous operation. To address this, you will need to create your own promise wrapper around it.

getGroupAllInfo(gatewayId: string, account: string, decryptedpasswd: string) {
  return new Promise((resolve, reject) => {
    cordova.plugins.MationPlugin.getGroupAllInfo(data, (response) => {
      const json: JSON = JSON.parse(response);
      resolve(json);
    }, (error) => {
      reject(error);
    });
})

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

Sending every piece of information to the URL may not be the most efficient approach, in my opinion

Lately, I have incorporated NodeJS into my Angular project and here is how I am currently implementing it: Node : app.get('/register/:username/:password', function(req, res){ db.collection('users').insertOne({ username: req ...

Angular 8: How to dynamically assign formControlName in HTML according to the component

Within my database table, I have a field named "key_name" which is successfully being returned through the API and working as expected. My goal is to set the value of these fields as a formControlName in the HTML. In the component, I am using a reactive f ...

Issue with Next.js 14: Server Component causing app crashes when tabs with ShadowCN are repeatedly fetched and changed

I'm currently developing a Next.js 14 application that utilizes ShadCN for UI components and TanStack Query for data fetching. The main screen of the app features a Tabs component that enables users to switch between different sections. One of these s ...

Using async await syntax, retrieve a file in string format via HTTP with Node.js

Is there a way to download a file into memory through http in nodejs without relying on third-party libraries? This response addresses a related issue, but I am interested in avoiding writing the file to disk. ...

Encountering a Typescript TypeError in es2022 that is not present in es2021

I'm attempting to switch the target property in the tsconfig.json file from es2015 to es2022, but I am encountering an error while running tests that seem to only use tsc without babel: Chrome Headless 110.0.5481.177 (Mac OS 10.15.7) TypeError: Can ...

Exploring the method to implement unit testing for a nested if condition using Karma-Jasmine within an Angular environment

I have a function and my unit test coverage is currently at 75%, but I am aiming for 100% coverage. This is the function in question: calculateRatingSummary(): void { if (this.averageRating > 0) { this.avgRatings = Math.trunc(this.averageRat ...

What steps can I take to ensure the reliable functioning of this npm script?

Within my npm package, I have these two straightforward scripts: "prebuild": "rimraf dist types", "build": "tsc", Development dependencies rimraf@^5.0.5 and typescript@^5.3.2 are both installed. However, when I run ...

Unable to retrieve information from ion-content within ion-footer

Update After some troubleshooting, I've found the solution. I realized that I needed to declare a $scope.get = {} outside of my save function and update <button ng-click="save(get)"></button> to simply <button ng-click="save()"> ...

Loading custom Angular modules results in an error

Seems like a simple thing, but I'm struggling to figure it out on my own. I have an Angular application with the following key files: app/app.module.ts app/dashboard/dashboard.component.html app/dashboard/stats-tile/stats-tile.component.html I used ...

NextJS and AWS Amplify collaboration for secure authentication routing

After hours of research, I'm struggling to navigate the authentication routing in NextJS combined with AWS Amplify. As a newcomer to NextJS, I want to implement a feature that disables the login/register page for users who are already logged in and pr ...

Is it possible to create a QR Code using Ionic 5?

Is there a way to generate QR Codes in Ionic 5? I attempted it, but keep receiving an error stating that the qrcode element is not recognized. Here is my code: qrcode.html <ion-item> <ion-input type="text" placeholder="My QR d ...

Eliminate JSON data that pertains to dates that are either in the past or future

I am working on integrating upcoming classes and past classes components into my application. I have successfully stored the schedule of classes and can retrieve them using backend services. However, I need to display only the upcoming classes in one compo ...

While trying to initialize a new Ionic project, a glitch arose during the npm subprocess execution for

I recently attempted to create a new Ionic project by following these steps: 1. Ran npm install -g @ionic/cli 2. Used the command 'ionic start' Unfortunately, I encountered some errors related to npm during this process. Despite my efforts to ...

How can one effectively import and save data from a CSV file into an array comprised of objects?

I am looking to read a CSV file and store it in a variable for future access, preferably as an array of objects. However, when trying the following code snippet: const csv = fs .createReadStream('data.csv') .pipe(csv.default({ separator: &ap ...

Is there a way to view the console in a released apk?

Currently working with Ionic and in need of exporting a release APK to be able to monitor the console for any potential issues. I am aware that using 'ionic cordova run --device' allows me to view the console, but it only shows a debug APK. Is t ...

Utilizing Typescript to filter a table and generate a transformed output for each item

What's the best way to return each mapped element of an array using an optimized approach like this: this.itemsList= res.map( ( x, index ) => { x.id = x.code; x.itemName = x.name; return x; }); I've tried optimizing it with a second me ...

Transitioning Web Application to Angular Version 2

I am currently in the process of transitioning a web application to Angular2. I have successfully transferred the HTML and CSS files to Angular's component.html and component.css respectively. However, I am encountering some difficulties with the .js ...

How to add icons to HTML select options using Angular

Looking for a way to enhance my component that displays a list of accounts with not only the account number, but also the currency represented by an icon or image of a country flag. Here is my current component setup: <select name="drpAccounts" class= ...

Is there a way to dynamically define the return type of a function in Typescript?

Can the variable baz be dynamically assigned the string type? type sampleType = () => ReturnType<sampleType>; // Want to return the type of any function I pass (Eg. ReturnType<typeof foo>) interface ISampleInterface { baz: sampleType; } ...

Display array elements in a PDF document using pdfmake

Upon reaching the final page of my Angular project, I have an array filled with data retrieved from a database. How can I utilize pdfmake to import this data into a PDF file? My goal is to display a table where the first column shows interv.code and the ...