简体   繁体   中英

Ionic how to get a Promise Reponse from a provider?

So I'm trying to get a response from a Promise in a Provider but I'm not having much luck.

My component never receives a response,

this.printerService.print(template).then(

            response => {

              console.log(response);

            }, err => {

             console.log(err);
        });

whilst my provider is returning true,

print(template): Promise<any> {
  return window.cordova.plugin.zebraprinter.print(address, join,
        function(success) { 

         return true;

        }, function(fail) { 

          return false;
        }
      );
}

You are not returning a promise which is what you seem to want.

print(template): Promise<bool> {
    return new Promise(resolve => {
        window.cordova.plugin.zebraprinter.print(address, join,
            success => resolve(true), // invokes .then() with true
            fail => resolve(false) // invokes .then() with false
        );
    });
}

exampleCall() {
    this.printerService.print(template).then(answer => console.log(answer));
}

If you want the promise to fail you can use the reject argument.

print(template): Promise<void> {
    return new Promise((resolve, reject) => {
        window.cordova.plugin.zebraprinter.print(address, join,
            success => resolve(), // invokes .then() without a value
            fail => reject() // invokes .catch() without a value
        );
    });
}

exampleCall() {
    this.printerService.print(template)
        .then(() => console.log('success'))
        .catch(() => console.log('fail'));
}

An easy way to achieve this, is by wrapping the zebraprinter function in a promise like so:

print(template): Promise<any> {
   return new Promise((resolve,reject)=> {
      window.cordova.plugin.zebraprinter.print(address, join,
       (success) =>  { 

         resolve(success)

        },(fail) => { 

          reject(fail)
        }
      );
   });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM