1

To handle promises I return and chain them with .then(). I must however use a third party library that expects a callback and that does not return a promise.

For clarity, a fake example:

person.sayHello()
    .then( response => introduceMyself() )
    .then( name => externalLibrary.storeAndGetInfo(name) )
    .then( info => saySomeInfo(info) )
    .catch( err => console.log(err) );

introduceMyself(){
   return asyncFunctionToGetAndSayMyName();
}

sayDomeInfo(info){
    console.log(info);
}

My problem is that externalLibrary.storeAndGetInfo expects these params:

storeAndGetInfo(string, callback(valueThatINeedForMyNextChainedFunction));

I have the feeling that I could wrap the external library function in a chainable function (one that returns a promise), and then use the library q to defer and resolve the callback function, but then I'm stuck as I don't know to actually implement it. Or is there another way?

PS in case it makes a difference, this is in a angularjs app

georgeawg
  • 48,608
  • 13
  • 72
  • 95
don
  • 4,113
  • 13
  • 45
  • 70
  • For the AngularJS framework use [Angular's $q Library](https://docs.angularjs.org/api/ng/service/$q) to make promises that are integrated with the AngularJS digest cycle. Promises from external libraries will cause subtle hard to debug problems. – georgeawg Mar 01 '17 at 13:39

1 Answers1

1

You should wrap your external library's call with a function that returns a a deferred promise:

function promisedStore (name) {
  var deferred = Q.defer(); //initialize deferred

  externalLibrary.storeAndGetInfo(name, function(error, result) {
    if (error) {
      deferred.reject(new Error(error)); //reject promise if error in cb
    } else {
      deferred.resolve(result); //resolve promise if no error in cb
    }
  });

  return deferred.promise; 
}
hackerrdave
  • 6,486
  • 1
  • 25
  • 29
  • 1
    Yes, that's it! I was close, but not close enough :-) will accept in 7 minutes – don Mar 01 '17 at 13:17
  • For the AngularJS framework use the [AngularJS $q Library](https://docs.angularjs.org/api/ng/service/%24q) to make promises that are integrated with the AngularJS digest cycle. Promises from external libraries will cause subtle hard to debug problems. – georgeawg Jul 12 '18 at 02:55