3
votes

I'm trying to make a JSON call with async/await using Cloud Functions for Firebase.

Any idea how to fix the following code? My plan is Blaze.

My inspiration is https://www.valentinog.com/blog/http-requests-node-js-async-await/

DEPLOY ERROR

functions[setDetails]: Deployment error.

const getDetails = async url => {

SyntaxError: Unexpected identifier at createScript (vm.js:56:10) at Object.runInThisContext (vm.js:97:10) at Module._compile (module.js:542:28) at Object.Module._extensions..js (module.js:579:10) at 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
what line is the error?Peter Haddad
@PeterHaddad line 9 till line 19.R. Martinez
@PeterHaddad In line 13 I tried to use ${data.results[0].details}. the same error happensR. Martinez
Error: Error occurred while parsing your function triggers. /home/MyID/MyFolder/functions/index.js:19 });R. Martinez
Can you edit the question to show the entire output from the deploy rather than just the one error log line?Doug Stevenson

2 Answers

1
votes

async/await is not yet supported natively by Cloud Functions. Cloud Functions runs node 6, which doesn't use a version of JavaScript that supports async/await. The deploy is failing because it doesn't know the async keyword.

Instead, you could initialize your project to use TypeScript, which supports async/await. The Firebase CLI will automatically transpile your code to ES6 that uses Promises to implement async/await.

0
votes

Another solution is rather than using async wait you could use another library called request-promise-any