Make the new stacktrace.js library synchronous

486 views Asked by At

I am using the new stacktracejs libary and it returns a promise.

StackTrace.get() // this results in a promise

Is there something I can do to make it synchronous?

like this:

var result = magicalSomething(StackTrace.get());
3

There are 3 answers

0
Eric Wendelin On BEST ANSWER

UPDATE: Benjamin's answer is more correct. Use this as of stacktrace.js v1.3.0

var stacktrace = StackTrace.getSync();

If you need synchronous behavior and don't care about guessing anonymous functions or source-map support or old IE, you can just use the stack parsing lib that underlies stacktrace.js - error-stack-parser this way:

function stacktrace() {
  try {
    throw new Error();
  } catch (e) {
    return ErrorStackParser.parse(e);
  }
}
6
Benjamin Gruenbaum On

Update: there is now a .getSync() for stack traces, it gives partial information but you can use it.

StackTrace.js works by making calls to the script files involved in the stack trace and extracting additional information for them. This means that you cannot obtain the stack trace it generates since a part is already asynchronous.

Technically, this is in fact solvable and could be made synchronous (at the price of freezing the page for tens of seconds) - however that does not appear to be a design goal of the library.

Instead, use what the library offers and use the given promise:

StackTrace.get().then(function(result) {
   // I got result here
});
0
Venryx On

Just wanted to mention that it is also possible to synchronously get the source-mapped stack-trace, with the stacktrace-js library.

It's not part of the API, but it's possible with some modifications.

See here: https://github.com/stacktracejs/stacktrace.js/issues/188