Javascript.地图Return

Javascript .map Return

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)

编辑:

经过一些评论后,我将其更改为以下内容,现在我得到了一些结果,它只是丑陋。我现在正在研究如何稍微清理它,所以我最终得到一个新的对象数组,其中包括存储编号和执行结果。

这也是 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() 通过调用方法并根据响应构建输出数组,将一个数组转换为另一个数组。

所以要改为使用 "external" 数组,您需要使用 for 循环而不是 .map()