首页 > 解决方案 > 并非所有代码路径都在 Firebase 云函数中返回值

问题描述

我正在使用 TypeScript 编写云函数。我想调用另一个第三方 API。我已经创建了如下所示的函数。

export const postData= functions.https.onRequest((req, response) => {
    if (req.method !== 'POST') {
        return response.status(500).json({
            message: 'not allowed'
        });
    }
    else {
        let phoneNumber = req.query.phoneNumber;
        request('https://api.xyz.com/api/insertData.php?authkey=xxxxxx&userid=' + phoneNumber,
         function (error: any, respon: any, body: any) {
            console.log(body);

        })
        .then(function(xyz:any){
            return response.status(200).json({
                dataPosted: true
            })
        })
        .catch(function(error:any){
            return response.status(200).json({
                dataPosted: false
            })
        })
    }
});

但是当我尝试部署我的函数时,它会显示“并非所有代码路径都返回一个值”。但是我在if&中都返回了响应else。我究竟做错了什么?请帮忙

标签: typescriptfirebasegoogle-cloud-functions

解决方案


您使用的请求库本机支持回调接口,但不返回承诺。

您可以使用request-promisehttps://github.com/request/request-promise)和rp()“返回符合常规 Promises/A+ 的承诺”的方法,然后按如下方式调整您的代码:

//......
import * as rp from 'request-promise';

export const postData = functions.https.onRequest((req, response) => {
  if (req.method !== 'POST') {
    return response.status(500).send('not allowed');
  } else {
    let phoneNumber = req.query.phoneNumber;

    var options = {
      url:
        'https://api.xyz.com/api/insertData.php?authkey=xxxxxx&userid=' +
        phoneNumber,
      method: 'POST'
    };

    return rp(options)
      .then(function(parsedBody: any) {
        response.send('data posted');
      })
      .catch(function(error: any) {
        console.log(error);
        response.status(500).send(error);
      });
  }
});

推荐阅读