我将如何在另一个http.request的响应中链接一个http.request,然后将它们推入数组,然后再进入前端?
router.get("/:team", (req, res) => {
let teamParams = teams[req.params.team];
twitter.get("search/tweets", teamParams, (err, data, resp) => {
let tweetArr = [];
let text = data.statuses;
text.map((dat) => {
let im = dat.entities.urls[0].url
dat.links = im;
tweetArr.push(dat);
});
res.json({ message: "Success", tweets: tweetArr });
});
});
当前,我通过它获取数据对象循环,并添加一个url作为属性。现在,我想在使用res.json之前,链接另一个http请求以对另一个API进行API调用并获得响应。 我已经尝试过使用Promise的解决方法,但是我永远无法返回带有第二个api调用响应的完整对象。
到目前为止,这是我已经设法达到的目的,我的对象包含来自第二个链接的请求。如何将所有tweet返回到最终可以解析的数组中?
require("dotenv").config();
const Twitter = require("twitter");
const API_IMAGE_PREV = "http://api.linkpreview.net/";
const request = require("request");
const key = process.env.IM_PREV_KEY;
let twitter = new Twitter({
consumer_key: process.env.TWITTER_CONSUMER_KEY,
consumer_secret: process.env.TWITTER_CONSUMER_SECRET,
bearer_token: process.env.TWITTER_BEARER_TOKEN
});
let teamParams = {
q: "from:ManUtdMEN MUFC",
count: 2,
result_type: "recent"
};
var third = function thirdUrl(next) {
var promise = new Promise(function(resolve, reject) {
next.forEach(x => {
let ln = x.links;
const options = {
url: "http://api.linkpreview.net/?key=" + key + "&q=" + ln,
method: "get"
};
request.get(options, (err, req, res) => {
if (err) {
console.log(err);
} else {
x.desc = res;
}
});
});
});
};
var second = function secondUrl(previous) {
var promise = new Promise(function(resolve, reject) {
let p = previous.statuses;
let links = [];
p.forEach(t => {
let l = t.entities.urls[0].url;
t.links = l;
});
resolve(p);
});
return promise;
};
twitter
.get("search/tweets", teamParams)
.then(second)
.then(third)
.catch(function(error) {
throw error;
});
答案 0 :(得分:1)
您用于http
请求的模块是什么?这是axios
的示例。
const axios = require('axios');
router.get("/:team", (req, res) => {
let teamParams = teams[req.params.team];
twitter.get("search/tweets", teamParams, async (err, data, resp) => {
let tweetArr = [];
let text = data.statuses;
text.map((dat) => {
let im = dat.entities.urls[0].url
dat.links = im;
tweetArr.push(dat);
});
let res = await Promise.all(tweetArr.map(dat => axios.get(dat.links));
res.json({ message: "Success", tweets: res });
});
})