`onStartedProcess`回调永远不会被调用

时间:2018-02-28 12:16:49

标签: javascript node.js

我用这段代码绑定一个函数

changeLabelAndReassign()

然后,在此过程中,当我调用此代码时

BarChart.vue

以下函数称为

this.process[id].on('started', this.onStartedProcess.bind(this)); // I    want to pass an extra variable here. 

在绑定时,是否可以将额外的变量传递给that.emit('started', {startTime:time, instance: that}); 函数?像

这样的东西
onStartedProcess(info) {
console.log(info.startTime);
}

并在因为emit而调用onStartedProcess时使用该参数,例如

this.process[id].on('started', this.onStartedProcess.bind(this,otherParameter));

我将这个post重新命名为绑定方法,但仍无法找到实现我想要的方法。

修改 这不适合我。这就是我试过的

onStartedProcess

onStartedProcess(info, otherParameter) { console.log(info.startTime); console.log(otherParameter); } 永远不会被称为

1 个答案:

答案 0 :(得分:1)

是。您正在描述bind函数的工作原理。首先传递上下文(this),然后传递所需的所有其他参数。 阅读文档here

问题在于您绑定的函数中的参数顺序。

onStartedProcess(info, otherParameter) {
    // with your current `.onStartedProcess.bind(this, 5)
    // you are binding `info` argument to `5`
    console.log(otherParameter); // I was expecting the get the 5 here
}

如果您想将otherParameter设置为5,则需要正确绑定第二个参数:.bind(thisArg, firstArg, SecondArg)

关于未调用的回调。 这是您的方案的一种解决方案:

// parent.js

const { fork } = require('child_process');
const subprocess = fork('child.js');

subprocess.send('start');
subprocess.send({ hello: 'world' });

// child.js

process.on('message', onStartedProcess.bind(null, 'first arg', 5));

function onStartedProcess(info, otherParameter, message) {
    console.info('callback args:', info, otherParameter, message);
}

运行node parent.js你应该得到这个输出:

  

callback args:first arg 5 start

     

callback args:first arg 5 {hello:'world'}

详细了解节点流程消息here

相关问题