帆v0.11.0(http://sailsjs.org/)sails.js找到async.js每個查詢,並行調用 - 每區選出早期
我曾嘗試不成功使用.exec回調,承諾(http://sailsjs.org/documentation/reference/waterline-orm/queries),現在async.js (https://github.com/caolan/async)來控制繞查找查詢循環的異步流。 async.each日誌輸出沒有並行工作(儘管並行填充)。
因此,如果您的解決方案使用.exec回調,promises或async.js - 我會很樂意接受它!
我發現這個鏈接給async.js(http://www.sebastianseilund.com/nodejs-async-in-practice)
謝謝您的時間和援助的一些有用的例子。
下面是使用異步我的代碼:
/**
* @module :: Service
* @type {{findProfile: Function}}
*/
require('async');
module.exports = {
getProfile: function (userId, callback) {
var json = {};
json.notFound = false;
json.locations = {};
json.sports = {};
User.findOne({id: userId}).exec(function (err, user) {
if (err) {
json.notFound = true;
json.err = err;
}
if (!err) {
json.user = user;
UserSport.find({user_id: user.id}).exec(function (err, userSports) {
if (err) {
sails.log.info("userSports error: " + userSports);
}
async.each(userSports, function (userSport, callback) {
LocationSport.findOne({id:userSport.locationsport_id}).exec(function (err, locationSport) {
if (locationSport instanceof Error) {
sails.log.info(locationSport);
}
async.parallel(
[
function (callback) {
Location.findOne({id:locationSport.location_id}).exec(function (err, location) {
if (location instanceof Error) {
sails.log.info(location);
}
callback(null, location);
});
},
function (callback) {
Sport.findOne({id:locationSport.sport_id}).exec(function (err, sport) {
if (sport instanceof Error) {
sails.log.info(sport);
}
callback(null, sport);
});
}
],
function (err, results) {
if (!(results[0].id in json.locations)) {
json.locations[results[0].id] = results[0];
}
if (!(results[1].id in json.sports)) {
json.sports[results[1].id] = results[1];
}
}
); // async.parallel
}); // locationSport
callback();
}, function (err) {
sails.log.info('each');
sails.log.info(json);
}); // async.each
}); // UserSport
}
}); // User
}
}
謝謝你@ arnaud-del。那樣做了。 – PgB