我有一堆异步调用,我想将其放入一个模块中并在另一个模块中使用结果。但似乎无法在带有 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/