Firebase Cloud函数打字稿中的异步等待问题

时间:2020-04-22 11:52:57

标签: javascript typescript firebase async-await google-cloud-functions

我正在从Web向下面提到的listingNumbers firebase云函数发送请求,我只传递了userData作为参数。 listingNumbers函数将调用一个api并在响应中获取一些数字。我能够在提到的numbers变量中获取数字,但是我无法将该值传递给前端,我得到了200条响应,我想我是错误的异步等待,我想将数字传递到前端,有人可以帮我吗,谢谢

import * as functions from 'firebase-functions';
import { request } from 'https';


export const listNumbers = functions.https.onRequest(async(req, resp) => {
const userData = req.query.user;
let str:string = '';

if(userData) {

    const req2 = await request(
    {
        host: 'url.com',
        port: '443',
        path: '/api/numbers/list-numbers?count=1',
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer token here',
        }
    },
    response => {

        response.on('data', function (chunk) {
            str += chunk;
        });

        response.on('end', function () {

            console.log(str);

            let jsonObj = JSON.parse(str);
            let numbers: string = jsonObj.numbers;
            // resp.send({'response':numbers});
            console.log(numbers);


        });
    },


    );

    try {
        resp.send({'response':'success'});
        console.log('reached try');
        req2.on('error', error => {
            console.error(error)
        });
        req2.end();
        // resp.send('success');

    }

    catch {
        resp.send({'response':'error'});
    }




}else {
    resp.send('unauthorized');
}

});

0 个答案:

没有答案