Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Example code from the video "Use async/await with TypeScript in Cloud Functions"

Example code from the video "Use async/await with TypeScript in Cloud Functions"

This is the example code from my video about using async/await with Cloud Functions. I've placed it here in a gist so it's easier to compare the "before" and "after" states for each case.

Watch the video here

The code in this project is licensed under the Apache License 2.0.

Copyright 2018 Google LLC
 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
 
    https://www.apache.org/licenses/LICENSE-2.0
 
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
export const getBostonWeather = functions.https.onRequest((request, response) => {
admin.firestore().doc("cities-weather/boston-ma-us").get()
.then(snapshot => {
const data = snapshot.data()
response.send(data)
})
.catch(error => {
// Handle the error
console.log(error)
response.status(500).send(error)
})
})
export const getBostonWeather = functions.https.onRequest(async (request, response) => {
try {
const snapshot = await admin.firestore().doc("cities-weather/boston-ma-us").get()
const data = snapshot.data()
response.send(data)
}
catch (error) {
// Handle the error
console.log(error)
response.status(500).send(error)
}
})
export const getBostonAreaWeather = functions.https.onRequest((request, response) => {
admin.firestore().doc("areas/greater-boston").get()
.then(areaSnapshot => {
const cities = areaSnapshot.data().cities
const promises = []
cities.forEach(city => {
const p = admin.firestore().doc(`cities-weather/${city}`).get()
promises.push(p)
})
return Promise.all(promises)
})
.then(snapshots => {
const results = []
snapshots.forEach(snap => {
const data = snap.data()
data.city = snap.id
results.push(data)
})
response.send(results)
})
.catch(error => {
console.log(error)
response.status(500).send(error)
})
})
export const getBostonAreaWeather = functions.https.onRequest(async (request, response) => {
try {
const areaSnapshot = await admin.firestore().doc("areas/greater-boston").get()
const cities = areaSnapshot.data().cities
const promises = []
cities.forEach(city => {
const p = admin.firestore().doc(`cities-weather/${city}`).get()
promises.push(p)
})
const snapshots = await Promise.all(promises)
const results = []
snapshots.forEach(snap => {
const data = snap.data()
data.city = snap.id
results.push(data)
})
response.send(results)
}
catch (error) {
console.error(error)
response.status(500).send(error)
}
})
@robmontesinos

This comment has been minimized.

Copy link

commented Aug 9, 2018

Thank you Doug!!

@DevilWarrior

This comment has been minimized.

Copy link

commented Aug 17, 2018

Hi,

When adding the async key to the function I get the error below, any ideas?

!  functions[process_payment(us-central1)]: Deployment 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:65
exports.mailReceived = functions.https.onRequest( async (req, res) => {
                                                        ^

SyntaxError: Unexpected token (
    at createScript (vm.js:56:10)
    at Object.runInThisContext (vm.js:97:10)
    at Module._compile (module.js:549:28)
    at Object.Module._extensions..js (module.js:586:10)
    at Module.load (module.js:494:32)
    at tryModuleLoad (module.js:453:12)
    at Function.Module._load (module.js:445:3)
    at Module.require (module.js:504:17)
    at require (internal/module.js:20:19)
    at getUserFunction (/var/tmp/worker/worker.js:388:24)
@DevilWarrior

This comment has been minimized.

Copy link

commented Aug 17, 2018

Never mind, It seems to be a discrepancy with node, let me update to the correct version.

@conormcelvaney

This comment has been minimized.

Copy link

commented Sep 17, 2018

Doug you are a legend, love your stuff, have just taken on Typescript because of your encouragement !

@predorock

This comment has been minimized.

Copy link

commented Oct 3, 2018

@devil

Never mind, It seems to be a discrepancy with node, let me update to the correct version.

Hi, I have the same problem with node, how do you fix it?

@quaternioninterpolation

This comment has been minimized.

Copy link

commented Dec 3, 2018

Incredible cheers

@ykabbara

This comment has been minimized.

Copy link

commented Feb 25, 2019

#Error

  • "Object is possibly 'undefined'.ts(2532)" error on line 9
  • "Variable 'results' implicitly has type 'any[]' in some locations where its type cannot be determined.ts(7034)" error on line 17
    and
  • "Variable 'results' implicitly has an 'any[]' type.ts(7005)" on line 23
    Anyone have the same problem or can help?
@Marcus-C137

This comment has been minimized.

Copy link

commented Apr 10, 2019

I'm having the same problem can't find a fix

@AndrsDev

This comment has been minimized.

Copy link

commented Apr 13, 2019

@Marcus-C137 for this to work you have to change these files in /functions directory to use ECMAScript2017

in .eslintrc.json

 "parserOptions": {
    // Required for certain syntax usages
    "ecmaVersion": 8
  },

and in package.json add

  "engines": {
    "node": "8"
  },

And then run npm install --save

@MeStrak

This comment has been minimized.

Copy link

commented May 11, 2019

@Marcus-C137 @ykabbara

I must admit that I haven't tested this, but I think you can fix it by defining the type in the array. From the code it looks like it should be an array of DocumentData objects.

add this import to index.ts if you don't have it to get firebase types:

import * as firebase from 'firebase';
And edit package.json to add in the firebase reference so it looks something like the following:

"dependencies": {`
   "firebase-admin": "~7.0.0",
   "firebase-functions": "^2.2.0",
   **"firebase": "^6.0.2"**
 },

Then edit the line where const results is created to read
const results: firebase.firestore.DocumentData [] = []

Like I said I didn't test this, so I'm not certain that DocumentData is the correct object type, You should be able to check it by calling typeof, and you can see the list in this doc: https://firebase.google.com/docs/reference/js/firebase.firestore.html.

I had a similar issue on my project when trying to pass a snapshot into an arrow function and fixed it by adding the type to the snapshot:
.then( (snapshot: firebase.firestore.QuerySnapshot) => {}

I hope that helps you and this isn't a red herring!

@choiseonjae

This comment has been minimized.

Copy link

commented May 16, 2019

Hey... I think you need to update the code. 'cause I'm also having trouble with the problem as same as above.
I can't fix the error 'ts2532'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.