$q.when angularjs code example

Example 1: $q use in angularjs

function MyService($q) {
  return {
    getSomething() {
      return $q((resolve, reject) => {
        if (/* some async task is all good */) {
          resolve('Success!');
        } else {
          reject('Oops... something went wrong');
        }
      });
    }
  };
}

angular
  .module('app')
  .service('MyService', MyService);

Example 2: $q use in angularjs

const handleThirdPartyCallback = someArgument => {
  let promise = new Promise((resolve, reject) => {
    // assuming some third-party API, that is *not* a Promise Object
    // but fires a callback once finished
    myCallbackLib(someArgument, response => {
      // we can resolve it with the response
      resolve(response);
    }, reason => {
      // we can reject it with the reason
      reject(reason);
    });
  });
  return promise;
};

handleThirdPartyCallback({ user: 101 }).then(data => {
  console.log(data);
});