如何等到某些值检索然后继续计算

时间:2017-12-11 10:53:10

标签: javascript node.js

在下面的代码中,我试图从['/ proc / meminfo']中读取名为'mapped'的特定值以及一个名为'nr_mapped'的特定值 [ '的/ proc / vmstat的']。然后我试图divid(映射/ nrMapped),如代码所示。

我遇到的问题是,当我运行代码时,首先执行此行

'   console.log('pageSize: ' + (Number(mapped) / Number(nrMapped))); '

它导致NaN

应该做什么,以便在执行procMeminfo和procVmstat之后执行先前声明的日志语句

结果

let mapped;
let nrMapped;
const { spawn } = require('child_process');
var process = require('process');

const procMeminfo = spawn('cat', ['/proc/meminfo']);
const procVmstat = spawn('cat', ['/proc/vmstat']);

procVmstat.stdout.on('data', (data) => {
//nr_mapped value
console.log('procVmstat:stdout: ' + 'processId: ' + process.pid + '-->' + data.toString().split('\n')[33]);
nrMapped = data.toString().split('\n')[33].replace(/[^\d.]/g, '');
console.log(nrMapped);
});

procMeminfo.stdout.on('data', (data) => {
console.log('procMeminfo:stdout: ' + 'processId: ' + process.pid + '-->' + data.toString().split('\n')[19]);
mapped = data.toString().split('\n')[19].replace(/[^\d.]/g, '');
console.log(mapped);
});

console.log('pageSize: ' + (Number(mapped) / Number(nrMapped)));

输出

pageSize: NaN

procMeminfo:stdout: processId: 12776-->Mapped:           321676 kB
321676
procVmstat:stdout: processId: 12776-->nr_mapped 80419
80419

1 个答案:

答案 0 :(得分:1)

利用Promises等待异步函数。

示例

let promises = [ ];

promises.push(new Promise((resolve, reject) => {
  procVmstat.stdout.on('data', (err, data) => {
    if (err) {
      return reject(err);
    }
    resolve(data);
    // repeat the same for the other method
}

promises.push(new Promise((resolve, reject) => {
  procMeminfo.stdout.on('data', (err, data) => {
    if (err) {
      return reject(err);
    }
    resolve(data);

}

Promise.all(promises).then((data) => {
  console.log(data)// get the data here and manipulate the same
}, err => {
  callback(err);
});