我在NodeJS上使用express,我想获得回调函数的结果。
function yts(s) {
return youTube.search(s, 5, function(error, result) {
var res;
var json = []
if (error) {
console.log(error);
res.send("error");
}
else {
//console.log(JSON.stringify(result, null, 2));
res = result["items"];
var i = 0;
while (res[i]) {
//console.log(i + " | " + res[i]["id"]["videoId"] + " | " + res[i]["snippet"]["title"] + " | " + "https://img.youtube.com/vi/"+ res[i]["id"]["videoId"] +"/0.jpg");
json.push({videoID: res[i]["id"]["videoId"], title: res[i]["snippet"]["title"]});
i++;
}
console.log(json);
//Get json
}
});
}
app.get('/search/:title', function (req, res) {
res.send(JSON.stringify(yts(req.params["title"])));
});
我正在使用youtube-node (NPM)搜索youtube,并将最重要的信息返回给用户。 如何使// Get json将代码以某种方式返回给app.get函数。
答案 0 :(得分:0)
您需要将函数转换为callback function,以便从YouTube检索到响应后立即返回。
let selectedMenuInfoObj = getMenuInfoByKey(this.state, '2019')
答案 1 :(得分:0)
使用将结果传递给的回调,或保证该功能并等待。
您还必须意识到,在yts
函数中,您无权访问res
,因此您无法执行res.send()
。
function yts(s, cb) {
youTube.search(s, 5, function(error, result) {
var res;
var json = []
if (error) {
console.log(error);
cb("error");
}
else {
//console.log(JSON.stringify(result, null, 2));
res = result["items"];
var i = 0;
while (res[i]) {
//console.log(i + " | " + res[i]["id"]["videoId"] + " | " + res[i]["snippet"]["title"] + " | " + "https://img.youtube.com/vi/"+ res[i]["id"]["videoId"] +"/0.jpg");
json.push({videoID: res[i]["id"]["videoId"], title: res[i]["snippet"]["title"]});
i++;
}
console.log(json);
cb(null, json);
//Get json
}
});
}
app.get('/search/:title', function (req, res) {
yts(req.params["title"], function(err, json){
if(err)
return res.send(err);
res.send(JSON.stringify(json));
})
});
async function yts(s) {
return new Promise((resolve, reject) => {
youTube.search(s, 5, function(error, result) {
var res;
var json = []
if (error) {
console.log(error);
reject("error");
}
else {
//console.log(JSON.stringify(result, null, 2));
res = result["items"];
var i = 0;
while (res[i]) {
//console.log(i + " | " + res[i]["id"]["videoId"] + " | " + res[i]["snippet"]["title"] + " | " + "https://img.youtube.com/vi/"+ res[i]["id"]["videoId"] +"/0.jpg");
json.push({videoID: res[i]["id"]["videoId"], title: res[i]["snippet"]["title"]});
i++;
}
console.log(json);
resolve(json);
//Get json
}
});
})
}
app.get('/search/:title', async function (req, res) {
try{
var json = await req.params["title"];
res.send(JSON.stringify(json));
}catch(err){
res.send(err);
}
});