【问题标题】:How do I return the value from a callback in this promise?如何从这个 Promise 的回调中返回值?
【发布时间】:2024-05-20 18:30:02
【问题描述】:

在我的 angularJS 4 应用程序中,我使用了一个名为 device motion 的 cordova 加速度计插件。该api有一个函数调用getAcceleration(successCallback,errorCallback)。所以我创建了一个看起来像这样的服务

 @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';
  }
}

在我的组件中,我这样做是为了尝试从 onSuccess 回调函数中获取返回值,但是响应未定义

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

我该如何解决这个问题?

【问题讨论】:

  • 你需要用结果来解决promise,而不是getCurrentAcceleration的返回。
  • 这应该使用 observalbes 解决
  • @Nickolaus 谢谢。我会更多地研究 observables

标签: javascript angular promise


【解决方案1】:

代替:

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

做:

this.acc.getCurrentAcceleration(resolve, reject);

你不需要this.onSuccess

【讨论】:

  • Promise 和回调让我很困惑。感谢您的帮助
【解决方案2】:

试试这样:

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

【讨论】: