简体   繁体   中英

How do I return the value from a callback in this promise?

In my angularJS 4 app, I'm using a cordova accelerometer plugin called device motion for something. The api has a function call getAcceleration(successCallback,errorCallback). So i created a service that looks like this

 @Injectable()
export class AccelerometerService {
  private acc : any;
  constructor(private winRef:WindowRef) { 
        this.acc = this.winRef.nativeWindow.plugins.navigator.accelerometer;
        this.onSuccess = this.onSuccess.bind(this);
        this.onError = this.onError.bind(this);
  }

  getAcceleration(){
    return new Promise ((resolve, reject) =>{
        resolve(this.acc.getCurrentAcceleration(this.onSuccess,this.onError));      
    });
  }
  onSuccess(acceleration){
    return acceleration;    // value that I want returned to my component
  }

  onError(){
        return 'error';
  }
}

In my component, I do this to try to get the return value from onSuccess callback function, however the response is undefined

 this.accelerationService.getAcceleration().then((res) =>{
              console.log(res); // res is undefined
          })

How can I resolve this issue?

Instead of:

resolve(this.acc.getCurrentAcceleration(this.onSuccess,this.onError));

Do:

this.acc.getCurrentAcceleration(resolve, reject);

You don't need this.onSuccess .

Try like this :

getAcceleration(): Promise<any> {
    return new Promise<any>((resolve, reject) => {
        this.acc.getCurrentAcceleration()
            .success(data => {
                resolve(<any>data);
            })
            .error(() => {
                reject('Failed to load profile');
            });
    })
}

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