How to get string representation of a variable as shown by console.log

Viewed 270

How do I get the string representation of a variable as shown when it's output by console.log()?

e.g.,

const myFunc = async () => 'my string';
ret = myFunc();
console.log(ret);  // Promise { 'my string' }
stringRepresentation = ret.someMethod(); // is there a method or some other way?
console.assert(stringRepresentation === "Promise { 'my string' }");

I'm primarily interested running this in Node.js (but also curious if it's possible when running in a browser).

2 Answers

Node.js console implementation uses util.inspect to stringify object output:

console.assert(util.inspect(ret) === "Promise { 'my string' }");

It's not safe to assert a promise to be Promise { 'my string' } because a promise is unnecessarily represented like that. In REPL it will be:

Promise {
  'my string',
  domain:
   Domain {
     domain: null,
     _events: { error: [Function: debugDomainError] },
     _eventsCount: 1,
     _maxListeners: undefined,
     members: [] } }

Even though util polyfill exists for browsers, it cannot be used to stringify promises synchronously because native promises cannot be inspected, only chained with then or catch. Node.js uses native bindings to inspect ES6 promises.

This is kind of a hack to your problem which will work for both browser and Node,

function assertPromise(promiseVal, stringVal) {
                promiseVal()
                        .then(str => {
                                let stringRepresentation = `Promise { '${str}' }`;
                                console.assert(stringRepresentation === stringVal);

                        });
}

const myFunc = async () => 'my string';

ret = myFunc();
console.log(ret);  // Promise { 'my string' }

assertPromise(myFunc, "Promise { 'my string' }");       // Assert to TRUE
Related