首页 > 解决方案 > 异步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);
});

我尝试使用回调,但我很困惑放置参数,因为实际上这也在回调内部。

标签: node.jsfirebaseasynchronousgoogle-cloud-functions

解决方案


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 theResponse` 对象,请参阅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”计划。


推荐阅读