2015-12-02 26 views
-1

中的NodeJS

arp.stdout.pipe(parse).pipe(filter).pipe(through(function(device) { 
 
    this.queue(device.mac + '\n'); 
 
    device_d.push(device.mac); 
 
}));

function CreateList() { 
 
    arp.stdout.pipe(parse).pipe(filter).pipe(through(function(device) { 
 
     this.queue(device.mac + '\n'); 
 
     device_d.push(device.mac); 
 
    })); 
 
    setTimeout(function() { 
 
     return device_d; 
 
    }, 1000); 
 
}

返回之前是没有得到执行这段代码运行功能同步。我总是得到一个空阵列。 我会得到只有在

arp.stdout.pipe(parse).pipe(filter).pipe(through(function(device) 
//{this.queue(device.mac + '\n');device_d.push(device.mac);})); runs synchronously. 
+1

你究竟在问什么? – MrHug

+0

这是一个问题或答案? – Technotronic

回答

0

为什么你需要setTimeout的反应?在函数CreateList()中,setTimeout不返回setTimeout。这是setTimeout中创建的函数的返回值。

如果你想使用同步功能,你应该使用deasync或类似的东西。

使用npm install deasync安装deasync并尝试此代码,它应该工作。

function CreateList() { 
    // variable for blocking loop until return value is ready 
    var ret = false; 

    arp.stdout.pipe(parse).pipe(filter).pipe(through(function(device) { 
     this.queue(device.mac + '\n'); 
     device_d.push(device.mac); 
     ret = true; // return values is ready, stop waiting loop 
    })); 

    while(!ret){ 
     require('deasync').runLoopOnce(); 
    } 

    return device_d; 
} 

console.log(CreateList()); 

但使用的是阻塞循环和一般同步功能不Node.js的建议

正确的方法是给这个函数转换为异步这样

function CreateList(callback) { 
    arp.stdout.pipe(parse).pipe(filter).pipe(through(function(device) { 
     this.queue(device.mac + '\n'); 
     device_d.push(device.mac); 
     callback(device_d); 
    })); 
} 

CreateList(function(response){ 
    console.log(response); 
}); 

更新:我没有意识到我在原始答案中用简单循环封锁了同步功能。你应该在循环内部使用deasync。