nodejs windows 执行承诺未决
nodejs windows exec promise pending
我 运行 exec
从计算机硬件中获取 ID。我正在尝试将 id 分配给变量 cpu_id 以便稍后可以在我的脚本中的 http 请求参数中使用它。当控制台日志似乎总是输出 Promise { <pending> }
而不是捕获的 id.
我尝试过 wait 和 async,但无法让事情按应有的方式运行。任何帮助或指点将不胜感激。
function get_cpu_id() {
if (process.platform === "win32") {
return execShellCommand('wmic csproduct get UUID /format:list').then(function(std){
return std.replace(/\s/g, '').split("=")[1];
});
} else {
return execShellCommand('cat /proc/cpuinfo | grep Serial').then(function(std){
return std;
});
}
}
function execShellCommand(cmd) {
const exec = require('child_process').exec;
return new Promise((resolve, reject) => {
exec(cmd, (error, stdout, stderr) => {
if (error) {
console.warn(error);
}
resolve(stdout ? stdout : stderr);
});
});
}
let cpu_id = get_cpu_id();
console.log(cpu_id);
执行 returns 承诺。
尝试使用 execSync
:
const execSync = require('child_process').execSync;
function get_cpu_id() {
if (process.platform === "win32") {
return execSync('wmic csproduct get UUID /format:list').toString();
} else {
return execSync('cat /proc/cpuinfo | grep Serial').toString();
}
}
let cpu_id = get_cpu_id();
console.log(cpu_id);
我 运行 exec
从计算机硬件中获取 ID。我正在尝试将 id 分配给变量 cpu_id 以便稍后可以在我的脚本中的 http 请求参数中使用它。当控制台日志似乎总是输出 Promise { <pending> }
而不是捕获的 id.
我尝试过 wait 和 async,但无法让事情按应有的方式运行。任何帮助或指点将不胜感激。
function get_cpu_id() {
if (process.platform === "win32") {
return execShellCommand('wmic csproduct get UUID /format:list').then(function(std){
return std.replace(/\s/g, '').split("=")[1];
});
} else {
return execShellCommand('cat /proc/cpuinfo | grep Serial').then(function(std){
return std;
});
}
}
function execShellCommand(cmd) {
const exec = require('child_process').exec;
return new Promise((resolve, reject) => {
exec(cmd, (error, stdout, stderr) => {
if (error) {
console.warn(error);
}
resolve(stdout ? stdout : stderr);
});
});
}
let cpu_id = get_cpu_id();
console.log(cpu_id);
执行 returns 承诺。
尝试使用 execSync
:
const execSync = require('child_process').execSync;
function get_cpu_id() {
if (process.platform === "win32") {
return execSync('wmic csproduct get UUID /format:list').toString();
} else {
return execSync('cat /proc/cpuinfo | grep Serial').toString();
}
}
let cpu_id = get_cpu_id();
console.log(cpu_id);