method.js (1768B)
1 "use strict"; 2 module.exports = 3 function(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug) { 4 var util = require("./util"); 5 var tryCatch = util.tryCatch; 6 7 Promise.method = function (fn) { 8 if (typeof fn !== "function") { 9 throw new Promise.TypeError("expecting a function but got " + util.classString(fn)); 10 } 11 return function () { 12 var ret = new Promise(INTERNAL); 13 ret._captureStackTrace(); 14 ret._pushContext(); 15 var value = tryCatch(fn).apply(this, arguments); 16 var promiseCreated = ret._popContext(); 17 debug.checkForgottenReturns( 18 value, promiseCreated, "Promise.method", ret); 19 ret._resolveFromSyncValue(value); 20 return ret; 21 }; 22 }; 23 24 Promise.attempt = Promise["try"] = function (fn) { 25 if (typeof fn !== "function") { 26 return apiRejection("expecting a function but got " + util.classString(fn)); 27 } 28 var ret = new Promise(INTERNAL); 29 ret._captureStackTrace(); 30 ret._pushContext(); 31 var value; 32 if (arguments.length > 1) { 33 debug.deprecated("calling Promise.try with more than 1 argument"); 34 var arg = arguments[1]; 35 var ctx = arguments[2]; 36 value = util.isArray(arg) ? tryCatch(fn).apply(ctx, arg) 37 : tryCatch(fn).call(ctx, arg); 38 } else { 39 value = tryCatch(fn)(); 40 } 41 var promiseCreated = ret._popContext(); 42 debug.checkForgottenReturns( 43 value, promiseCreated, "Promise.try", ret); 44 ret._resolveFromSyncValue(value); 45 return ret; 46 }; 47 48 Promise.prototype._resolveFromSyncValue = function (value) { 49 if (value === util.errorObj) { 50 this._rejectCallback(value.e, false); 51 } else { 52 this._resolveCallback(value, true); 53 } 54 }; 55 };