我有一个带有mean.js的端点,它运行在数组中传递的多个查询,我想运行每个查询并只返回一个promise,我使用map创建每个响应,最后我想响应所有的结果承诺与承诺。所有。
['72.438', '109.283', '43.980']
['75.664', '110.907', '45.079']
['74.354', '111.094', '48.594']
['73.380', '107.449', '48.722']
['76.614', '106.603', '46.958']
['79.740', '105.625', '48.895']
['82.425', '107.703', '47.318']
['80.088', '110.405', '46.265']
['78.710', '110.389', '49.818']
['82.235', '110.471', '51.200']
['82.841', '113.550', '49.133']
['79.233', '114.754', '49.675']
['78.633', '113.745', '53.295']
['77.041', '117.182', '53.503']
['73.963', '116.530', '51.505']
['73.696', '113.058', '52.933']
TypeError: Cannot cast array data from dtype('float64') to dtype('<U32') according to the rule 'safe'
问题是每个promises都处于暂挂状态和Promise.all()。然后永远不会来。
答案 0 :(得分:0)
你误用Promise
(函数)。它接受的回调是接受resolve
和reject
参数的回调。该回调的返回值不用于任何事情。但你对它的看法有点像then
回调。
db.sequelize.query
已经返回一个承诺,您无需将其包装在另一个承诺中,请参阅***
行:
var db = require(path.resolve('./config/lib/sequelize'));
exports.runQueries= function (req, res, queries) {
// queries os an array
var runQueries = function(query){
// *** Just return the promise
return db.sequelize.query(query, { type: db.Sequelize.QueryTypes.SELECT });
};
var actions = queryFn.map(runQueries);
Promise.all(actions).then(function(data){
res.send(data);
});
};
当然,这可以简单得多:
var db = require(path.resolve('./config/lib/sequelize'));
exports.runQueries= function (req, res, queries) {
// queries is an array
var actions = queries(query => db.sequelize.query(query, { type: db.Sequelize.QueryTypes.SELECT }));
Promise.all(actions).then(data => {
res.send(data);
});
};
附注:data
回调中的Promise.all
将是来自db.sequelize.query
各种已解决承诺的结果的数组。您确定可以直接将该数组传递到res.send()
吗?