【发布时间】:2023-04-03 11:25:02
【问题描述】:
给定以下值数组:
var sportList = ['football', 'volleyball'];
我想使用以下每个值在 mongo 数据库上运行查询:
function myFunc(sport, callback) {
mongoDB.sports.find({'name': sport}, function (error, result) {
if (error) {
callback(error)
} else {
callback(null, result)
}
})
}
所以我建立了我的承诺,例如:
var promises = sportList.map(function(val){
return myFunc(val);
});
然后尝试在一个 Promise all 链中运行 all:
Promise.all(promises)
.then(function (result) {
console.log('log results: ', result);
})
.catch(function (error) {
console.log(error);
});
但这不起作用,因为它抱怨 callback 未定义,我该如何正确解决这个问题?
【问题讨论】:
-
为了使用
Promise.all,你实际上应该有一个promise数组。myFunc不返回任何内容,因此目前您有一个undefined值数组。你必须让它返回一个承诺。 -
callback是未定义的——你没有向它传递值。你期待会发生什么? -
另外,如果你确实提供了一个回调,promise 将是一个
undefined的数组...... Promise.all 理想情况下应该提供一个 Promises 的数组......myFunc与承诺 -
尝试将 myFunc 更改为
const myFunc = sport => new Promise((resolve, reject) => mongoDB.sports.find({'name': sport}, (error, result) => error ? reject(error) : resolve(result))); -
或者,如果使用最新的 nodejs(我在这里假设 nodejs)...将
const myFuncAsync = utils.promisify(myFunc)添加到您的代码中并使用var promises = sportList.map(myFuncAsync)
标签: javascript arrays callback promise