Promisifying API callbacks - How to properly resolve or reject

不打扰是莪最后的温柔 提交于 2021-02-16 21:00:35

问题


I've read similar posts, but none quite hit on the head how to do this correctly.

I understand Promises and how they are typically created with success and failure listeners waiting to be triggered to either resolve or reject.

What I don't understand is when I'm calling an API method that takes a success and failure callback as parameters- how do I determine which callback is being triggered so I can then have it resolved or rejected?

For example with this Web API and considering the navigator.geolocation.getCurrentPosition method it offers:

var options = {
  enableHighAccuracy: true,
  timeout: 5000,
  maximumAge: 0
};

function success(pos) {
  var crd = pos.coords;

  console.log('Your current position is:');
  console.log('Latitude : ' + crd.latitude);
  console.log('Longitude: ' + crd.longitude);
  console.log('More or less ' + crd.accuracy + ' meters.');
};

function error(err) {
  console.warn('ERROR(' + err.code + '): ' + err.message);
};

navigator.geolocation.getCurrentPosition(success, error, options);

When the API sends back a success or error it will call one of the callbacks I gave it but I don't know which one it's gonna call in order resolve or reject it.

The question is then: What is the proper way to listen for which callback is being triggered and how does it look to ES6 promisify the outcome of this kind of API call?


回答1:


Something like that:

function getCurrentPositon(options){
   return new Promise(function(resolve, reject){   
     navigator.geolocation.getCurrentPosition(resolve, reject, options);
   });
}

You don't know which one is called, rather, you respond to both options - rejecting if it fails and fulfilling if it fulfilled.



来源:https://stackoverflow.com/questions/32893871/promisifying-api-callbacks-how-to-properly-resolve-or-reject

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!