node.js - 返回 promise 结果的模块

标签 node.js asynchronous module return export

我有一堆异步调用,我想将其放入一个模块中并在另一个模块中使用结果。但似乎无法在带有 Promise/Callback 的异步调用中使用返回值。

module.exports = function () {
  Promise.all(data_promises).then(/* do stuff with data */)
  // return data ?
}

在另一个模块中:

var getData = require('async-module')
var data = getData()

是否可以使用单独的模块?

<小时/>

实际代码:

module.exports = function () {

  agentsSheet.useServiceAccountAuthAsync(creds).then(function(){

    var data_promises = priceCols.map(function (col) {
      return agentsSheet.getCellsAsync(1, {
        'min-row': 2,
        'max-row': 30,
        'min-col': col,
        'max-col': col,
        'return-empty': false
      })
    })

    Promise.all(data_promises).then(function (data) {
      var rawData = _.flattenDeep(data)
      var priceOptions = {}

      _.forEach(rawData, function (item) {
        priceOptions[item.value] = (priceOptions[item.value] + 1) || 1
      })

      var priceOptionsSorted = _.sortKeysBy(priceOptions, value => -value)

      console.log(priceOptionsSorted);
    })
  })
}

最佳答案

你只需要添加2个返回:

module.exports = function () {
  // one
  return agentsSheet.useServiceAccountAuthAsync(creds).then(function(){
    var data_promises = priceCols.map(function (col) {
      return agentsSheet.getCellsAsync(1, {
        'min-row': 2,
        'max-row': 30,
        'min-col': col,
        'max-col': col,
        'return-empty': false
      })
    })

    // two
    return Promise.all(data_promises).then(function (data) {
      var rawData = _.flattenDeep(data)
      var priceOptions = {}

      _.forEach(rawData, function (item) {
        priceOptions[item.value] = (priceOptions[item.value] + 1) || 1
      })

      var priceOptionsSorted = _.sortKeysBy(priceOptions, value => -value);

      console.log(priceOptionsSorted);
    });
  });
}

现在,所需的模块是一个 promise :

var getData = require('async-module');
// then() will run when the Promise.all() is resolved
var data = getData().then(/* do some stuff */);

关于node.js - 返回 promise 结果的模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35726160/

相关文章:

python - 随机模块没有属性 'choices'

node.js - 停止测试运​​行 mocha

javascript - 关于集群消息触发类函数

javascript - Node JS 的 Promises 数组仍处于 <pending> 状态

python - 为什么我的协程会阻塞整个 Tornado 实例?

javascript - requireJS - 几个问题

Angular2 - 多个模块的共享布局

javascript - 观察对象变化的最低级别方法

node.js - webpack-cli 未知参数 : --output

javascript - jQuery 等待两个触发器