对于 Node 库,我希望能够将日志函数传递给返回 Promise 的函数。默认情况下,记录器将是 console.log
,但可能会被其他内容替换,具体取决于用例。
// define custom logger
const opts = {
log: console.log,
error: console.error
};
const spawnPromise = (cmd, args, opts) => {
return new Promise((resolve, reject) => {
const child = spawn(cmd, args, opts);
child.stdout.on('data', (data) => {
// use custom log function
opts.log(stringify(data));
});
child.stderr.on('data', (data) => {
// use custom error function
opts.error(stringify(data));
});
child.on('close', (code) => {
if (code === 0) {
resolve();
} else {
reject();
}
});
});
};
这会导致以下错误:
Uncaught Exception: test.js
TypeError: opts.log is not a function
Socket.<anonymous>
我做错了什么?
最佳答案
opts
在 spawnPromise
内不是 opts
你已经在上面声明了,它是你为 spawnPromise
声明的参数这里:
const spawnPromise = (cmd, args, opts) => {
// ------------------------------^^^^
该参数隐藏了模块全局。 spawnPromise
将使用您传递给它的内容,而不是全局模块。如果要使用全局模块,请更改它的名称或参数。
也许(见 <===
评论):
// define custom logger
const defaultOpts = { // <=== Change name
log: console.log,
error: console.error
};
const spawnPromise = (cmd, args, opts) => {
opts = Object.assign({}, defaultOpts, opts); // <=== Expand with defaults
return new Promise((resolve, reject) => {
const child = spawn(cmd, args, opts);
child.stdout.on('data', (data) => {
// use custom log function
opts.log(stringify(data));
});
child.stderr.on('data', (data) => {
// use custom error function
opts.error(stringify(data));
});
child.on('close', (code) => {
if (code === 0) {
resolve();
} else {
reject();
}
});
});
};
请注意 Object.assign
如果 opts
将忽略它是null
或 undefined
(而不是导致错误)。
用Stage 3 proposal , 那Object.assign
可以改用传播:
opts = {...defaultOpts, ...opts};
在目前的形式中,opts
也没有问题。正在null
或 undefined
.但同样,传播属性目前只是第 3 阶段。
关于javascript - 将日志功能传递给 Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46388661/