如何获取变量的字符串表示形式,就像console.log所显示的那样

7

我该如何得到一个变量的字符串表示形式,就像在 console.log() 输出时所显示的那样?

例如:

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' }");

我主要关注在Node.js中运行它(但也好奇在浏览器中运行是否可能)。


4
严格来讲,控制台不会输出“字符串表示”。对于许多对象,它会输出交互式对象检查器。Promise { 'my string' } 可能是其中一个特殊的检查器。因此,对于你的问题,大多数情况下的答案是“不”。 - deceze
ret = myFunc().then(val => console.log(val))。 - user9181162
谢谢@deceze。我主要想在Node.js中运行它——这是否使得获取字符串表示更加可能? - Rob Bednark
2个回答

4

Node.js控制台实现使用util.inspect来字符串化对象输出:

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

断言一个promise为Promise { 'my string' }是不安全的,因为promise没有必要被表示成这样。在REPL中它将是:

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

即使浏览器存在 util polyfill,它也不能用于同步地将 promises 转换为字符串,因为原生 promises 无法被检查,只能使用 thencatch 进行链式操作。Node.js 使用本地绑定来检查 ES6 promises,具体实现请参考这里


2
点赞指出Promises不支持同步内省。 - Patrick Roberts

0

这是一种对于你的问题的“hack”,它可以同时在浏览器和 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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接