sampleGroupOfStores is an array of 100 objects
The console logs inside the map show things correct
but console.log(storeResults) is just an array of 100 undefined items
I think I'm not returning things correctly here inside map to make the new array of objects storeResults.
Any tips would be greatly appreciated.
i removed any sensitive data from the script below
I was using .forEach but I decided .map is what I wanted because I want to take sampleGroupOfStores and get a new array of objects out of it based on the criteria in the if statements below.
The setTimeOut was because I was thinking the console.log(storeReults) was running before the map fully finished.
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)
EDIT:
After some comments I change it to below and I now have some results it's just ugly. I'm working out how to clean it up a bit now so I end up with a new array of objects that include, store number and exec results.
Also this is the NPM for exec https://www.npmjs.com/package/node-ssh-exec
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)
execfunction's callback, notmapfunction's callback.sampleGroupOfStores.mapdoesn't return anything.... anyways, you cannot synchronously map an array and perform an asynchronous call in the map function. You should look into promises andPromise.all.execreturns?execis synchronous. If it's asynchronous, what you're trying to do isn't possible, you'll have to return a promise or allow for a callback.