[英]How to fix null parameters when emitting to async listeners in node.js's event library?
我有三個js類:我的事件對象類正在導出,一個類具有發出功能,另一個類是構造函數中的偵聽器。 我有三個偵聽器正在使用setImmediate()
使它異步。 第一個偵聽器能夠正確獲取參數,而其他兩個則無法。
我嘗試在setImmediate()
回調之前將其打印出來,並且能夠看到正確的參數。
bus.on('event', (input) => {
setImmediate(() => {
function(input); //parameter are not null here
});
}, this);
bus.on('event', (input) => {
//console.log(input) when printing the input here, I can see the values
setImmediate(() => {
function2(input); //null
});
}, this);
bus.on('event', (input) => {
setImmediate(() => {
function3(input);
});
}, this);
我除input
為[e1, e2, e3
,但實際輸出為null
如果在進入事件處理程序時input
是好的,但是在setImmediate()
之后input
不是好的,那么代碼中的其他內容必須先更改數組,然后才能使用它。 這有在異步代碼中傳遞可變對象的危險。
為了避免這種情況,您可以復制該陣列,以便其他任何人都不能更改它。
bus.on('event', (input) => {
// make copy of input so nobody else will change it
let inputCopy = input.slice();
setImmediate(() => {
function2(inputCopy);
});
}, this);
注意:如果您的數組包含對象,並且這些對象本身可能已被其他人更改,則上面的副本將無法保護您。
您也可以通過不使用setImmediate()
並僅同步處理數組來避免此問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.