javascript - 如何在回调函数中获取回调函数的结果
问题描述
我在 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 函数。
解决方案
使用将结果传递给的回调,或承诺函数并等待它。
您还必须意识到,在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);
}
});
推荐阅读
- eclipse-plugin - Eclipse plugin to associate a file extension to the HTML editor
- python - ruamel.yaml:如何在顶层和其他元素内添加新元素
- java - 龙目岛与来自camelCase的Jackson Deserializer
- python - 如果与列表中每个字典中一个键的值匹配,则将新键添加到具有来自不同字典的值的字典列表
- ios - 将 uipagecontrol 连接到我的整个 uicollectionview,而不是连接到单个单元格
- apostrophe-cms - 使用引导程序时撇号-cms 不显示小部件
- python - 无法在 Python 中打破 while 循环
- java - Java Servlet 更改显示的 URL
- javascript - 将数据从firebase检索到javascript
- python - Python if(a & !b): 语法?