【问题标题】:how to get data in promise { } object如何在 promise {} 对象中获取数据
【发布时间】:2019-12-09 18:33:29
【问题描述】:

我使用 node.js。

我在 async 模块中使用并行方法来控制异步。

在每个任务函数中,运行python代码并获取结果。

但该结果包含在 Promise 对象中。

代码

const tasks = [
    function(callback) {
        pythonShell.run(options, (err, jsonArray)=> {
            callback(null, jsonArray)
        }
    },
    function(callback) {
        pythonShell.run(options, (err, jsonArray)=> {
            console.log(jsonArray) //1
            callback(null, jsonArray)
        }
    }
]

async.parallel(tasks, (err, results) => {
    if (err) return err.message
    console.log(results)//2
});

第一个 console.log

Promise {
    [{...}, {...}]
}

第二个控制台.log

[
    Promise {
        [{...}, {...}]
    },
    Promise {
        [{...}, {...}]
    }
]

我只想要 Promise { ... } 中的 json 数组

我怎样才能得到它?

【问题讨论】:

  • 尝试用Promise.all(results).then(console.log)替换console.log(results)
  • 只需使用.then(array => { /* Do something with the array of results */ })

标签: node.js asynchronous parallel-processing promise


【解决方案1】:

使用 .then((array_of_data_variable) => {

您想要的操作在这里(显示给用户,保存到 json 等)

}

这是使用 ES6 语法风格。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-14
    • 1970-01-01
    • 2022-11-27
    相关资源
    最近更新 更多