Gathering detailed insights and metrics for when-traceable
Gathering detailed insights and metrics for when-traceable
Gathering detailed insights and metrics for when-traceable
Gathering detailed insights and metrics for when-traceable
Promises/A+ solution with traceable fused that ease debugging to async code
npm install when-traceable
Typescript
Module System
Node Version
NPM Version
JavaScript (100%)
Total Downloads
0
Last Day
0
Last Week
0
Last Month
0
Last Year
0
MIT License
1 Stars
8 Commits
1 Watchers
1 Branches
Updated on Aug 23, 2016
Latest Version
0.2.3
Package Id
when-traceable@0.2.3
Size
42.60 kB
NPM Version
2.14.7
Node Version
4.2.1
Cumulative downloads
Total Downloads
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year
This is an Promises/A+ solution with traceable fused that ease debugging to async code.
Returns a Promise/A+ object that is to be fulfilled or rejected in the future or immediately. Specifically promise objects created by this library relies on the promise package.
However for arguments that requires a promise object, any objects of Promise/A+ implementation should work.
All errors raised during asynchronous callback are all processed by the traceable package so you can access the stack trace of the previous event loop.
1when(function (then) { 2 fs.readFile('/inexist/path', then(function (data) { })); 3}).catch(function (err) { 4 console.log(err.stack); // Error: ENOENT: ... at Error (native) 5 console.log(err.asyncStack); // Error at myfile.js:2:35 at ... 6});
With handler and fulfilling value:
Error
object is returned, follow the error handling routine.undefined
fulfill with handler.With handler and error:
Error#name
or Error#code
) is one of the keys:
string
, reject with an error with the new code and same message.function
, follow the error handling routine again.default
key presents on the map:
1when(promise, function (value) { 2 return anotherPromise; // Take the state of `anotherPromise` 3 return anotherValue; // Fulfull with `anotherValue` 4 throw new Error(); // Call `onerror` if supplied or reject with error 5}); 6when(promise, function (value) { 7 console.log(value); // Tap on fulfillment 8}); 9when(promise, null, function (err) { 10 return anotherPromise; // Take the state of `anotherPromise` 11 return value; // Fulfill with `value` instead of rejection 12 throw new Error(); // Reject with new error 13}); 14when(promise, null, function (err) { 15 console.log(err); // Tap on rejection 16}); 17when(promise, null, { 18 ETIMEOUT: function () { 19 return null; // Ignore ETIMEOUT error 20 }, 21 default: 'ENOENT' // Throw ENOENT in case of any other errors 22}); 23 24// Combining `then` and `onerror` 25when(promise, function (value) { 26 /* `onerror` will be called with the raised exception */ 27 throw new Error(); 28}, function (err) { 29 /* Reach here when promise is fulfilled or rejected */ 30});
It is very similar to calling Promise#then(then, onerror)
except that
onerror
can catch any exceptions or errors from then
; andthen
and onerror
.So retry can be easily written as
1var retryCount = 0; 2when(promise, doSomething, function (err) { 3 // When retried less than 5 times 4 // run again and let the promise to follow the state again 5 // if `doSomething` fails again this error handler will be called again 6 if (++retryCount < 5) { 7 return doSomething(); 8 } 9});
when(fn, [onerror])
Runs the callback fn
and returns a promise object.
1when(function (then) { /* do something */ });
The fn
function receives a function argument then
.
The primary usage of then
is to deal with Node.js callback pattern.
If then
is called with handler
, it returns a callback function that handles Node.js callback where:
onerror
as handler.handler
as handler and null action being doing nothing.1// Promise fulfilled with the file size 2when(function (then) { 3 fs.stat('/path/to/file', then(function (data) { 4 return data.size; 5 })); 6}); 7 8// Promise fulfilled with `fs.Stats` 9when(function (then) { 10 fs.stat('/path/to/file', then()); 11}); 12 13// Promise that check if the file exists and then read the file content 14when(function (then) { 15 fs.stat('/path/to/file', then(function (data) { 16 fs.readFile('/path/to/file', then()); 17 // Does not return anything so the promise is not fulfilled at this time 18 // promise will be fulfilled with file content when callback of `fs.readFile` is called 19 })); 20});
when(value, [then], [onerror])
If none of the overloads listed below matches, returns a fulfilled promise with value
.
then
and onerror
will be supplied as handlers for resolving routine and
error handling rountine.
when(Promise, [then], [onerror])
Returns a promise that wait until the given promise is fulfilled or rejected, and resolve the promise by resolving routine with the fulfilled value as handler.
1// Promise fulfilled with 2 2when(promiseOne, function (value) { 3 assert(value === 1); 4 return value * 2; 5});
when(Array<Promise>, [then], [onerror])
Returns a promise that wait until all promises are fulfilled or rejected:
If more than one promise is rejected, other errors will sinked silently.
To catch the sinked errors use when.monitor
.
1when([promiseUndefined, promiseOne, promiseTwo], function (data) { 2 assert(data.length === 3); // Outcome array has the same length 3 assert(data[0] === undefined); // Undefined result stay in the correct index 4 assert(data[1] === 1); 5 assert(data[2] === 2); 6});
when(Object<Promise>, [then], [onerror])
Returns a promise that wait until all promises are fulfilled or rejected:
If more than one promise is rejected, other errors will sinked silently.
To catch the sinked errors use when.monitor
.
1when({ 2 one: promiseOne, 3 two: promiseTwo 4}, function (data) { 5 assert(data.one === 1); 6 assert(data.two === 2); 7});
when(EventEmitter, [eventHandlers], [onerror])
Returns a promise that:
EventEmitter
emits an error
event, follow the error handling routine with the error.1// Fulfill when response emit `end` event with the first argument 2// Reject when response emit `error` event 3when(response, 'end'); 4 5// Fulfill when response emit `end` event with custom value 6when(response, 'end', function () { 7 return state; 8}); 9 10// Fulfill on multiple event 11when(response, { 12 end: function () { /* ... */ }, 13 close: function () { /* ... */ } 14});
when(Array<Function>)
Returns a promise that sequentially calls the functions.
The promise will always be resolved after call on the last element.
Any exception raised in callback
will not break the asynchronous loop.
To catch the sinked errors use when.monitor
.
1when([printOne, printTwo, printThree]); // Print out "123"
when(Error)
Returns a rejected promise with the given error.
when.map(array, callback, [then], [onerror])
Calls callback
on each element in the array
, creating promise objects on each value from the calls, and
returns a promise that wait until all promises are fulfilled or rejected.
1// Promise fulfilled with [1, 4, 9] 2when.map([1, 2, 3], function (number) { 3 return squarePromise(number); 4}); 5 6// Both the immediately returned promises and the fulfilled values of the promises 7// are flatten if their elements contains arrays 8// the following promise is fulfilled with [2, 3, 1, 4, 6, 4, 6, 9, 9] 9when.map([1, 2, 3], function (number) { 10 return [ 11 doubleAndTriplePromise(number), 12 squarePromise(number) 13 ]; 14}); 15 16// Promises and values can be mixed on the map callback 17// the following promise is fulfilled with [1, 4, 3] 18when.map([1, 2, 3], function (number) { 19 return isOdd(number) ? number : doublePromise(number); 20});
when.forEach(array, callback, [then], [onerror])
Sequentially calls callback
on each element in the array after the promise returned from the last call is fulfilled or rejected.
The promise will always be resolved after call on the last element.
Any exception raised in callback
will not break the asynchronous loop.
To catch the sinked errors use when.monitor
.
1// `arr` will contain the exact sequence of numbers as the input array 2var arr = []; 3when.forEach([1, 2, 3, 4, 5], function (number) { 4 return delayRandomPromise(function () { 5 arr.push(number); 6 }); 7});
when.while(fn, [then], [onerror])
Asychronous version of while((value = fn(value)) !== false)
.
The fulfilled value returned from the fn
callback will be tested and as the parameter of the next call to fn
.
1var result = []; 2when.while(function (pageIndex) { 3 return when(getPagedResult(pageIndex || 0), function (data) { 4 Array.prototype.push.apply(result, data.items); 5 // If there is next page of results return the next page index 6 // `fn` will be called with the returned page index 7 if (data.hasNextPage) { 8 return (pageIndex || 0) + 1; 9 } 10 // Return `false` to end the asynchronous loop 11 // Can also return a promise if it is not immediately available 12 return false; 13 }); 14}, 15// Resolve the promise from `when.while` by the combined results 16result);
when.monitor([options], callback)
By this the returned promise object is exteneded with EventEmitter
so you can listen various event.
timeout
eventIf timeout
options is specified, the timeout
event is emitted when one of the promise in the promise chain
did not fulfill or reject in the given amount of time.
The error object is raised with call stack information about the promise creation location.
1when.monitor({ 2 // timeout in milliseconds 3 timeout: 10000 4}, function () { 5 return wontFulfillPromise(); 6}).on('timeout', function (err) { 7 // prints call stack where the promise has been created 8 console.log(err.asyncStack); 9});
uncaughtException
eventThe uncaughtException
event is emitted when creating a promise from an array of promise, where
only the first encountered error is propagated through the promise chain.
The other errors they are considered uncaught and will be sinked silently. By attaching a monitor you can catch those errors.
1when.monitor(function () { 2 return when([ 3 rejectPromise(), 4 rejectPromise(), 5 rejectPromise() 6 ]); 7}).on('uncaughtException', function (err) { 8 // uncaughtException event will be emitted two times 9});
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
0 existing vulnerabilities detected
Reason
license file detected
Details
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
Found 0/8 approved changesets -- score normalized to 0
Reason
no SAST tool detected
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Score
Last Scanned on 2025-07-07
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More