我需要在我的 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);
}
});
};
最佳答案
首先,让函数返回一个 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);
});
});
关于javascript - 如何在 express.js 中将回调放入 res.json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52367803/