我已经用node.js实现了宁静的api,但是在api响应之后,我需要从回调方法中获取响应,我必须使用song_id来获取详细歌手。
下面是我的songs.js文件
99901
我正在song_details.js下面调用导出模块
var express = require('express');
var router = express.Router();
var moviecontents = require("./movies_content.js");
router.get('/:id', function(req, res) {
res.locals.connection.query('select song_id, song_title, song_duration from view_song_movie_mapping where movie_id=? ORDER BY song_id ASC',[req.params.id], function (error, results, fields) {
if(error){
res.send(JSON.stringify({"status": 500, "error": error, "response": null}));
} else {
var aResult = [];
var aResultNew = [];
for (var i in results){
var myreq = new Object();
myreq.song_id = results[i].song_id;
myreq.role_id = 1556;
aResult.push(results[i]);
moviecontents.getSongPersonView(myreq, res, function(err, dataval){
if(err) throw err;
aResultNew.push(dataval);
});
}
res.send(JSON.stringify({"status": 200, "error": null, "response": aResult}));
}
});
});
module.exports = router;
我想使用第一个查询中的song_id来将该Song_id用于下一个查询,并将结果附加为响应,但是响应在导出模块执行之前就已执行
答案 0 :(得分:0)
//Here is the answer
var express = require('express');
var router = express.Router();
var async = require("async");
function getSongSingerDetails (song_id,res) {
return new Promise(function(resolve, reject){
res.locals.connection.query('SELECT person_id, person_name FROM view_song_person_mapping WHERE song_id = ? and role_id = ? order by song_person_id DESC',[song_id,1556], function (error, results, fields) {
if(error){
res.send(JSON.stringify({"status": 500, "error": error, "response": null}));
} else {
resolve(results);
}
});
});
}
function getSongListing (req, res) {
return new Promise(function(resolve, reject){
res.locals.connection.query('select song_id, song_title, song_duration from view_song_movie_mapping where movie_id=? ORDER BY song_id ASC',[req.params.id], function (error, results, fields) {
if(error){
res.send(JSON.stringify({"status": 500, "error": error, "response": null}));
} else {
resolve(results);
}
});
});
}
async function getsongdetails(req, res){
var songlist = await getSongListing(req, res);
for (var i=0; i<songlist.length; i++) {
var singerdetails = await getSongSingerDetails(songlist[i].song_id,res);
songlist[i]['singers'] = [];
songlist[i]['singers'] = singerdetails;
}
res.send({"status": 200, "error": null, "response": songlist});
}
router.get('/:id', function(req, res) {
var results = getsongdetails(req, res);
});
module.exports = router;