1

I found this example:

Callback:

getDetails('Bob', function (err, details) {
   console.log(details)
});

To Promise:

getDetails('Bob').then(function (details) {
   console.log(details);
});

example callback to promise

but not work for me.

How do I convert callbacks to promises in javascript or angularjs?

Thanks!

alvarezsh
  • 503
  • 3
  • 8
  • 21
  • before giving link, describe a little bit more. – Enamul Hassan Jul 26 '15 at 00:13
  • This sounds like an X-Y problem. Should show what the function getDetails does first as well as explain what you are wanting to do at a bit higher level. If `getDetails` returns a `$resource` for example then you would need to work with the documented `$resource` api and actually provide 2 callbacks – charlietfl Jul 26 '15 at 00:39

1 Answers1

2
getDetails('Bob').then(function (details) {
   console.log(details);
});

This work only if getDetails return a promise. To create a promise you need $q service.

So getDetails should looks like:

function getDetails(name){

    var defered = $q.defer();

    defered.resolve('BobDetails');

    return defered.promise;

}

Your callback will be called when the promise is resolved, and as param it will get 'BobDetails' in this example.

sylvain1264
  • 855
  • 2
  • 8
  • 23