Search code examples
firebasegoogle-cloud-functionsfirebase-cli

async function with cloud functions (syntax error on async)


I have the following code in my index.js:

exports.queryAPI = functions.https.onRequest((request, response) => {
  return cors(request, response, () => {
    return APICall(request.params.searchTerm).then((result) => {
        console.log(result);
        return result;
      }).catch(() => {
        return response.status(400).json({ error: 'Something went wrong.' });
      })
  });
});

async function APICall(search) {
  const response = await apicalypse({
    queryMethod: "body",
    headers: {
      'Accept': 'application/json',
      'user-key': API_KEY
    },
    responseType: 'json',
    timeout: 1000,
    })
    .fields(["name"]) // fetches only the name and movies fields
    .search(search) // search for a specific name (search implementations can vary)

    // .where("age > 50 & movies != n") // filter the results
    // .where(["age > 50", "movies != n"]) // same as above
    .request(API_URL);

  return response.data;
}

When I try to deploy this function I get the following error:

Function load error: Code in file index.js can't be loaded.
Is there a syntax error in your code?
Detailed stack trace: /user_code/index.js:34
async function APICall(search) {
      ^^^^^^^^

SyntaxError: Unexpected token function

According to my searches I did the function correct with async. Someone that point where I made my mistake?


Solution

  • You're probably using a node version less than 8 on your local machine. Version 8 is the first version that supports ES7 async/await syntax. So, the first thing is to update your local node installation. Check the version with node --version.

    Cloud Functions uses node 6 as a runtime by default, so if you want your deployed code that uses async/await to run, you will also have to tell the Firebase CLI to target node 8. Node 8 support is in beta. You can read about targeting node 8 in the documentation and in this blog.