如何在Firebase的云功能中进行HTTP请求async / await?

时间:2018-03-05 19:24:15

标签: json firebase async-await google-cloud-functions axios

我正在尝试使用Cloud Functions for Cloudbase与async / await进行JSON调用。

知道如何修复以下代码吗?我的计划是Blaze。

我的灵感来自https://www.valentinog.com/blog/http-requests-node-js-async-await/

部署错误

  

functions [setDetails]:部署错误。

     

const getDetails = async url => {

     

SyntaxError:意外的标识符       在createScript(vm.js:56:10)       在Object.runInThisContext(vm.js:97:10)       在Module._compile(module.js:542:28)       在Object.Module._extensions..js(module.js:579:10)       在Module.load(module.js:487:32)       at require(internal / module.js:20:19)       at getUserFunction(/var/tmp/worker/worker.js:378:24)

INDEX.JS

'use strict';
const functions = require('firebase-functions');
const admin = require('firebase-admin');    
// Promise based HTTP client for the browser and node.js
const axios = require('axios');

admin.initializeApp(functions.config().firebase);
const url = 'https://api.xxxx.com/json?partnumber=';
const getDetails = async url => {
    try {
        const response = await axios.get(url);
        const data = response.data;
        const getDet = data.results[0].details;
        return getDet;
    } catch (error) {
        console.log(error);
        return error;
    }
};
exports.setDetails = functions.database.ref('/equipment/{pushId}').onWrite((event) => {
  const post = event.data.val();
  if (post.details){ return };
  const number = post.number;
  const details = getDetails(url + number);
  admin.database().ref('/equipment/{pushId}').push({number: number, details: details});
});

的package.json

{
  "name": "look-at-details",
  "description": "bla bla bla",
  "dependencies": {
    "axios": "^0.18.0",
    "firebase-admin": "^5.9.1",
    "firebase-functions": "^0.8.1"
  },  
  "scripts": {
    "serve": "firebase serve --only functions",
    "shell": "firebase experimental:functions:shell",
    "start": "npm run shell",
    "deploy": "firebase deploy --only functions",
    "logs": "firebase functions:log"
  }
}

2 个答案:

答案 0 :(得分:1)

云功能本身尚不支持

async / await。云功能运行节点6,该节点不使用支持async / await的JavaScript版本。部署失败,因为它不知道async关键字。

相反,您可以初始化项目以使用支持async / await的TypeScript。 Firebase CLI将自动将您的代码转换为使用Promises实现async / await的ES6。

答案 1 :(得分:0)

另一个解决方案是使用另一个名为request-promise-any

的库,而不是使用async wait