sampleGroupOfStores 是一个包含 100 个对象的数组
map 内的控制台日志显示内容正确
但是 console.log(storeResults) 只是一个包含 100 个未定义项目的数组
我认为我没有在 map 内正确返回内容以创建新的对象数组 storeResults。
任何提示将不胜感激。
我从下面的脚本中删除了所有敏感数据
我使用的是 .forEach,但我决定 .map 是我想要的,因为我想获取 sampleGroupOfStores 并根据下面的 if 语句中的条件从中获取一个新的对象数组。
setTimeOut 是因为我认为 console.log(storeReults) 在 map 完全完成之前运行。
const storeResults = sampleGroupOfStores.map( config => {
exec(config, command, (error, response) => {
if(error) {
console.log('ERROR: Store: ', config.store, ' Message: ', error.level)
return config.store + error.level
}
const mac1 = _.includes(response, 'MAC ADDRESS')
const mac2 = _.includes(response, 'MAC ADDRESS')
const mac3 = _.includes(response, 'MAC ADDRESS')
if(response && mac1 || mac2 || mac3) {
console.log(config.store, 'MAC PRESENT')
return config.store + 'MAC PRESENT'
} else {
console.log(config.store, 'No MAC PRESENT')
return config.store + 'No MAC PRESENT'
}
})
} )
setTimeout( () => {console.log(storeResults)}, 10000)
编辑:
经过一些评论后,我将其更改为下面的内容,现在我得到了一些结果,它只是丑陋。我现在正在研究如何清理它,以便最终得到一个新的对象数组,其中包含、存储数字和执行结果。
这也是 exec https://www.npmjs.com/package/node-ssh-exec 的 NPM
const storeResults = sampleGroupOfStores.map( config => {
const storeInfo = []
exec(config, command, (error, response) => {
if(error) {
//console.log('ERROR: Store: ', config.store, ' Message: ', error.level)
storeInfo.push({store: config.store, message: error.level })
}
const mac1 = _.includes(response, 'MAC ADDRESS')
const mac2 = _.includes(response, 'MAC ADDRESS')
const mac3 = _.includes(response, 'MAC ADDRESS')
if(response && mac1 || mac2 || mac3) {
//console.log(config.store, 'MAC PRESENT')
storeInfo.push({store: config.store, message: 'MAC PRESENT'})
} else {
//console.log(config.store, 'No MAC PRESENT')
storeInfo.push({store: config.store, message: 'No MAC PRESENT'})
}
})
return storeInfo
} )
setTimeout( () => {console.log(storeResults)}, 10000)
最佳答案
查看 exec() 的代码,您不会从中获得任何值(exec()
的结果将始终是 undefined
由于该结果被传回 map
添加到最终结果中......您将得到一组 undefined
.
看来您需要重新考虑您的策略,以便从回调中更新数组。
我倾向于按照你正在考虑的方式去做results = []
- 然后在回调内部,我使用 results.push(usefulValue)
当您这样做时,您会想要停止使用 .map()
.map()
通过调用方法并根据响应构建输出数组,将一个数组转换为另一个数组。
因此,要更改为使用“外部”数组,您需要使用 for 循环而不是 .map()
关于JavaScript .map 返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47041381/