我需要调用异步回调函数来返回Express.js中的对象,但是我不知道该怎么做!
app.get('/first', function (req, res, next) {
res.json(//put my async callback function here ?);
});
功能:
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);
}
});
};
答案 0 :(得分:2)
首先,使函数返回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);
}
});
});
};
此后,调用异步函数并在拥有数据后运行res.json()
:
app.get('/first', function (req, res, next) {
reqObj().then(data => {
res.json(data);
}).catch(err => console.log(err));
});
res.json()
仅接受对象作为其参数
这是带有回调的解决方案
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);
});
});
答案 1 :(得分:0)
您通过异步函数将json放在那里
const x = async () => await {some: 'value'};
response.json(x())