Reputation: 2692
I have a script that's reading a bunch of info from Firebase, and then
processes it. This involves some async calls to external data sources, for which I want to use async
and await
. I've done this successfully, in this very npm project, so I don't see why it's not working now. This is my .babelrc file:
{
"presets": ["es2015", "stage-0", "react"],
"plugins": ["syntax-async-functions","transform-regenerator"]
}
And this is the gist of my code:
var config = {
apiKey: "key",
authDomain: "myProject.firebaseapp.com",
databaseURL: "https://myProject.firebaseio.com",
storageBucket: "myProject.appspot.com",
messagingSenderId: "id"
};
Firebase.initializeApp(config);
var dbRef = Firebase.database().ref();
getAllFirebaseDocs(dbRef);
async function getAllFirebaseDocs(dbRef) {
return dbRef.once('value').then(function(snapshot) {
var items = snapshot.val();
for (key in items) {
var priceUrl = "some.url.com"
items[key] = await requestPrices(items[key], priceUrl);
}
}
}
It's failing on the await
line with SyntaxError: testScript.js: Unexpected token
. And a bunch of code with weird box characters and 33m and 39m in it, like this: [33m][39m[1m,[22m priceUrl[94m[1m)[22m[39m[1m;[22m
.
I'm running the script with babel-node testScript.js
. I know this works, since I have another script that I run in the same project with babel-node
and it has async parts that work fine... not sure what I've missed in this one. If it matters, babel-node -V
gives v6.4.0.
Upvotes: 0
Views: 183
Reputation: 203241
You can only use await
within functions that are marked async
. In your case, you're running it inside a function (the callback to .then()
) that isn't marked as such.
You can use this:
return dbRef.once('value').then(async function(snapshot) { ... });
But since you're using async/await
already, you might as well rewrite your code to this:
async function getAllFirebaseDocs(dbRef) {
let snapshot = await dbRef.once('value');
let items = snapshot.val();
for (let key in items) {
let priceUrl = "some.url.com"
items[key] = await requestPrices(items[key], priceUrl);
}
// I assume that you want to return `items`; your original code doesn't return anything.
return items;
}
Upvotes: 2