node.js - 如何进行双重请求?
问题描述
如何在 Nodejs 中进行双重请求?
function script() {
request(`https://hacker-news.firebaseio.com/v0/item/8863.json`, function
(error, res, body) {
if(error) {
console.log(error)
} else {
console.log(JSON.parse(body))
}
})
}
这是我的代码,我想再次请求查找标题。有人有想法吗?
解决方案
最简单的方法是在第一个请求的回调函数中发出请求。
function script() {
request('https://hacker-news.firebaseio.com/v0/item/8863.json', function (error, res, body) {
if (error) {
console.log(error);
} else {
console.log(JSON.parse(body));
var titleUrl = '';
request(titleUrl, function (err, res, body) {
if (err) {
console.log(err);
} else {
console.log(JSON.parse(body));
}
});
}
});
}
这对于简单的应用程序来说很好,但它很快就会变得笨拙和丑陋。我建议学习 Promise API。您将需要一个不同的请求库,request
因为它本身不支持 Promises。根据经验,如果可以的话,我建议使用got
.
function script() {
got('https://hacker-news.firebaseio.com/v0/item/8863.json')
.then(function (response) {
console.log(JSON.parse(response.body));
let titleUrl = "";
return got(titleUrl)
})
.then(function(response) {
console.log(JSON.parse(response.body));
})
.catch(function (error) {
console.log(error);
});
}
推荐阅读
- angular - 如何将 Angular 升级到最新版本?
- python - 将 pandas 列定位或移动到特定列索引
- powerbi - 如何通过从 Power BI 中的数据日志文件中筛选相似数据组的最新日期来计算累积平均值?
- python - 如何根据字典中已有的内容将键和值迭代到字典中
- typescript - 用玩笑测试打字稿中的私有函数
- dart - 如何从文件中获取字节数据
- python - 错误“对象没有属性”与类
- multiprocessing - 如何包装 ProcessPoolExecutor 以使其允许非守护进程
- reactjs - 单元测试错误:字段必须在用 reduxForm() 装饰的组件内
- java - 在 SpringBoot 中使用 swagger.yaml 的 Swagger UI