node.js - 异步http调用后更新变量值
问题描述
我有一个名为firebase 的函数,其中包含使用request npm 包的getRequest
简单 http 调用和一个名为的变量,该变量应包含请求完成后来自 http 调用的主体响应。
但是,输出是一个字符串,因为 http 调用是异步运行的。
如何让变量包含来自 http 调用的主体响应?result
request
"this should be replaced"
result
const functions = require('firebase-functions');
const request = require('request');
exports.getRequest = functions.https.onRequest(() => {
let result = "this should be replaced";
request('http://worldclockapi.com/api/json/est/now', function(error,response,body){
if (!error && response.statusCode == 200)
result = body;
});
console.log(result);
});
我尝试使用回调,但我很困惑放置参数,因为实际上这也在回调内部。
解决方案
request
原生支持回调接口,但不返回 promise。在发回响应之前,您必须等待对外部 API 的异步调用完成,为此您应该使用 Promise,它将在对 API 的调用返回时解析。
您可以使用“返回常规 Promises/A+ 兼容承诺”的request-promise
库和rp()
方法,然后按如下方式调整您的代码:
const functions = require('firebase-functions');
const rp = require('request-promise');
exports.getRequest = functions.https.onRequest((req, res) => {
let result = "this should be replaced";
var options = {
uri: 'http://worldclockapi.com/api/json/est/now',
json: true // Automatically stringifies the body to JSON
};
rp(options)
.then(parsedBody => {
result = parsedBody.currentDateTime;
console.log(result);
res.send( {result} );
})
.catch(err => {
// API call failed...
res.status(500).send({'Error': err});
});
});
我建议您观看官方视频系列 ( https://firebase.google.com/docs/functions/video-series/ ),其中解释了有关返回 Promise 的关键点以及如何处理 HTTP 云函数中的错误。
需要额外注意两点:
onRequest()
论据
您需要将两个参数传递给onRequest()
函数:Request and the
Response` 对象,请参阅https://firebase.google.com/docs/functions/http-events?authuser=0#trigger_a_function_with_an_http_request
exports.date = functions.https.onRequest((req, res) => {
// ...
});
定价计划
您需要使用“Flame”或“Blaze”定价计划。
事实上,免费的“Spark”计划“只允许向 Google 拥有的服务发出出站网络请求”。请参阅https://firebase.google.com/pricing/(将鼠标悬停在“云功能”标题后面的问号上)
由于 worldclock API 不是 Google 拥有的服务,因此您需要切换到“Flame”或“Blaze”计划。
推荐阅读
- reactjs - Jest 无法解析 CSS 样式表
- vb.net - 从 VB.NET 中的注册表获取实际 REG_DWORD 十进制数的另一种方法?
- r - 逐行创建data.table
- json - 使用不同 JSON 的内容作为输入以使用 jq 进行修改
- javascript - 如何解决反应数组映射功能错误?
- jsf - 验证器未显示在咆哮或消息中
- python - 我在卸载 pytorch 时遇到问题
- logstash - Logstash 过滤器出错,kibana 不显示新日志
- javascript - Jquery.BuildFragment() 私有化。再次使用此功能的最佳方法是什么?
- c# - 使用 C# 解析八位字节流/SNMP