Code coverage report for lib/deps/toPromise.js

Statements: 100% (29 / 29)      Branches: 100% (12 / 12)      Functions: 100% (7 / 7)      Lines: 100% (29 / 29)      Ignored: none     

All files » lib/deps/ » toPromise.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55    2 2 2   1   32692 67196 67196     67196 67196     21503 21503 21503       67196 67196 67196 67196 65678 9884   55794         67196 67196 67186 7710     10       67196 21503 16453     67196       2
'use strict';
 
var Promise = require('./promise');
var getArguments = require('argsarray');
var once = require('./once');
 
function toPromise(func) {
  //create the function we will be returning
  return getArguments(function (args) {
    var self = this;
    var tempCB =
      (typeof args[args.length - 1] === 'function') ? args.pop() : false;
    // if the last argument is a function, assume its a callback
    var usedCB;
    if (tempCB) {
      // if it was a callback, create a new callback which calls it,
      // but do so async so we don't trap any errors
      usedCB = function (err, resp) {
        process.nextTick(function () {
          tempCB(err, resp);
        });
      };
    }
    var promise = new Promise(function (fulfill, reject) {
      var resp;
      try {
        var callback = once(function (err, mesg) {
          if (err) {
            reject(err);
          } else {
            fulfill(mesg);
          }
        });
        // create a callback for this invocation
        // apply the function in the orig context
        args.push(callback);
        resp = func.apply(self, args);
        if (resp && typeof resp.then === 'function') {
          fulfill(resp);
        }
      } catch (e) {
        reject(e);
      }
    });
    // if there is a callback, call it back
    if (usedCB) {
      promise.then(function (result) {
        usedCB(null, result);
      }, usedCB);
    }
    return promise;
  });
}
 
module.exports = toPromise;