1

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?

3 Answers 3

3

Node.js version 8 is required. Do this on your development machine:

nvm install 8.6.1
nvm alias default 8.6.1

Then in your functions directory, open package.json and add:

  "engines": {
    "node": "8"
  },
Sign up to request clarification or add additional context in comments.

Comments

2

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.

1 Comment

That was indeed my mistake. I had add target Node 8 on the Firebase CLI. Added "engines": {"node": "8"} and it deployed successfully.
0

I'm not sure the reason, but the await command only works in index.js for me. If I move the same command to another file and exports the function, I get the same compilation error as your async error.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.