[英]How to put callback into res.json in express.js
I need to call asynchronous callback function that return object in my Express.js, but I don't know how! 我需要调用在我的Express.js中返回对象的异步回调函数,但是我不知道该怎么做!
app.get('/first', function (req, res, next) {
res.json(//put my async callback function here ?);
});
The function: 功能:
const reqObj = () => {
request(`isdb.pw/${url}`, function(err, res, body) {
if (!err) {
const $ = cheerio.load(body);
var name = $('meta[name="description"]').attr('content');
var story = $('meta[property="og:video:url"]').attr('content');
return {
name,
story
};
} else {
console.log(err);
}
});
};
First, make the function return a Promise, then you can use .then on it: 首先,使函数返回Promise,然后可以使用.then:
const reqObj = () => {
return new Promise((resolve, reject) => {
request(`isdb.pw/${url}`, function(err, res, body) {
if (!err) {
const $ = cheerio.load(body);
var name = $('meta[name="description"]').attr('content');
var story = $('meta[property="og:video:url"]').attr('content');
resolve({
name,
story
});
} else {
reject(err);
}
});
});
};
After that call the asynchronous function and run res.json()
once you have the data: 之后,调用异步函数并在res.json()
数据后运行res.json()
:
app.get('/first', function (req, res, next) {
reqObj().then(data => {
res.json(data);
}).catch(err => console.log(err));
});
res.json()
only accepts Objects as it's parameter res.json()
仅接受对象作为其参数
Here is a solution with callbacks 这是带有回调的解决方案
const reqObj = (callback) => { // <-- add callback parameter here request(`isdb.pw/${url}`, function(err, res, body) { if (!err) { const $ = cheerio.load(body); var name = $('meta[name="description"]').attr('content'); var story = $('meta[property="og:video:url"]').attr('content'); callback(null,{ // <-- call callback function without err, but with data name, story }); } else { callback(err); // <-- call callback just with data } }); }); }; app.get('/first', function(req, res, next) { reqObj((err, data) => { // <-- pass callback function if(err) return console.log(err) // <-- check for error res.json(data); }); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.