简体   繁体   中英

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?

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"
  },

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM