Rob*_*ark 7 javascript string node.js
如何获取变量输出时所示的字符串表示形式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' }");
Run Code Online (Sandbox Code Playgroud)
我主要感兴趣的是在 Node.js 中运行它(但也很好奇在浏览器中运行时是否可能)。
Node.js 控制台实现用于util.inspect字符串化对象输出:
console.assert(util.inspect(ret) === "Promise { 'my string' }");
Run Code Online (Sandbox Code Playgroud)
断言 Promise 是不安全的,Promise { 'my string' }因为 Promise 没有必要这样表示。在 REPL 中它将是:
Promise {
'my string',
domain:
Domain {
domain: null,
_events: { error: [Function: debugDomainError] },
_eventsCount: 1,
_maxListeners: undefined,
members: [] } }
Run Code Online (Sandbox Code Playgroud)
尽管util浏览器存在polyfill,但它不能用于同步地字符串化promise,因为无法检查本机promise,只能与thenor链接catch。Node.js使用本机绑定来检查 ES6 Promise。