【发布时间】:2018-04-12 23:24:11
【问题描述】:
sampleGroupOfStores 是一个包含 100 个对象的数组
地图内的控制台日志显示正确
但是 console.log(storeResults) 只是一个包含 100 个未定义项的数组
我想我没有在 map 中正确返回东西来创建新的对象数组 storeResults。
任何提示将不胜感激。
我从下面的脚本中删除了所有敏感数据
我使用的是 .forEach,但我认为 .map 是我想要的,因为我想获取 sampleGroupOfStores 并根据下面 if 语句中的条件从中获取一个新的对象数组。
setTimeOut 是因为我认为 console.log(storeReults) 在地图完全完成之前正在运行。
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)
编辑:
在一些 cmets 之后,我将其更改为以下,现在我得到了一些结果,它只是丑陋。我现在正在研究如何清理它,所以我最终得到了一个新的对象数组,其中包括存储编号和执行结果。
这也是 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函数的回调返回对象,而不是map函数的回调。 -
您传递给
sampleGroupOfStores.map的函数不返回任何内容......无论如何,您无法同步映射数组并在映射函数中执行异步调用。你应该看看 promises 和Promise.all。 -
@theGleep:你认为
exec的回报是什么? -
好的,所以我需要在 exec 之外构建 results = [],然后在 if 语句中的 exec 内部构建,我可以推送 config.store + message 或类似的东西?
-
@SirFry 仅当
exec是同步的。如果它是异步的,那么您尝试做的事情是不可能的,您必须返回一个承诺或允许回调。
标签: javascript arrays node.js ecmascript-6 array.prototype.map