pushRef.set() is not a function, Firebase query - javascript

This is my code:
var pushRef = currentAssignment.child('answers').push().catch(e => console.log('push', e));
pushRef.set({
// downloadURL: downURL,
textAnswer: textAnswer,
date: this.generateDate(),
seen: false,
// firebaseKey: pushRef.getKey(),
workKey: this.props.questionId
})
When I try to run it, I get this error: pushRef.set(), but according to this part of the documentation it looks to me like I'm doing everything the same way. Here's Google's example of push instruction:
var postsRef = ref.child("posts");
var newPostRef = postsRef.push();
newPostRef
.set({
author: "gracehop",
title: "Announcing COBOL, a New Programming Language"
});
// we can also chain the two calls together
postsRef
.push()
.set({
author: "alanisawesome",
title: "The Turing Machine"
});
So what am I missing?

By adding .catch(e => console.log('push', e)) behind push() you change it from a firebase database reference to something else. So removing that will fix this.
As far as I know calling push() (without parameters) will never generate an error, it simply generates a firebase reference (unique key) client side.

Your code is expecting that catch() returns a database reference. It doesn't - catch() always returns a promise.
The use of catch here is unnecessary because push() with no arguments is a completely local operation. It returns a database reference that can also be used like a promise (a ThenableReference).
If there is any error to possibly catch here, it's on the promise returned by set(). That call will fail if security rules are violated during the write operation.

Related

New to graphql, trying to find a single item from array of objects [duplicate]

I have an graphql/apollo-server/graphql-yoga endpoint. This endpoint exposes data returned from a database (or a REST endpoint or some other service).
I know my data source is returning the correct data -- if I log the result of the call to the data source inside my resolver, I can see the data being returned. However, my GraphQL field(s) always resolve to null.
If I make the field non-null, I see the following error inside the errors array in the response:
Cannot return null for non-nullable field
Why is GraphQL not returning the data?
There's two common reasons your field or fields are resolving to null: 1) returning data in the wrong shape inside your resolver; and 2) not using Promises correctly.
Note: if you're seeing the following error:
Cannot return null for non-nullable field
the underlying issue is that your field is returning null. You can still follow the steps outlined below to try to resolve this error.
The following examples will refer to this simple schema:
type Query {
post(id: ID): Post
posts: [Post]
}
type Post {
id: ID
title: String
body: String
}
Returning data in the wrong shape
Our schema, along with the requested query, defines the "shape" of the data object in the response returned by our endpoint. By shape, we mean what properties objects have, and whether those properties' values' are scalar values, other objects, or arrays of objects or scalars.
In the same way a schema defines the shape of the total response, the type of an individual field defines the shape of that field's value. The shape of the data we return in our resolver must likewise match this expected shape. When it doesn't, we frequently end up with unexpected nulls in our response.
Before we dive into specific examples, though, it's important to grasp how GraphQL resolves fields.
Understanding default resolver behavior
While you certainly can write a resolver for every field in your schema, it's often not necessary because GraphQL.js uses a default resolver when you don't provide one.
At a high level, what the default resolver does is simple: it looks at the value the parent field resolved to and if that value is a JavaScript object, it looks for a property on that Object with the same name as the field being resolved. If it finds that property, it resolves to the value of that property. Otherwise, it resolves to null.
Let's say in our resolver for the post field, we return the value { title: 'My First Post', bod: 'Hello World!' }. If we don't write resolvers for any of the fields on the Post type, we can still request the post:
query {
post {
id
title
body
}
}
and our response will be
{
"data": {
"post" {
"id": null,
"title": "My First Post",
"body": null,
}
}
}
The title field was resolved even though we didn't provide a resolver for it because the default resolver did the heavy lifting -- it saw there was a property named title on the Object the parent field (in this case post) resolved to and so it just resolved to that property's value. The id field resolved to null because the object we returned in our post resolver did not have an id property. The body field also resolved to null because of a typo -- we have a property called bod instead of body!
Pro tip: If bod is not a typo but what an API or database actually returns, we can always write a resolver for the body field to match our schema. For example: (parent) => parent.bod
One important thing to keep in mind is that in JavaScript, almost everything is an Object. So if the post field resolves to a String or a Number, the default resolver for each of the fields on the Post type will still try to find an appropriately named property on the parent object, inevitably fail and return null. If a field has an object type but you return something other than object in its resolver (like a String or an Array), you will not see any error about the type mismatch but the child fields for that field will inevitably resolve to null.
Common Scenario #1: Wrapped Responses
If we're writing the resolver for the post query, we might fetch our code from some other endpoint, like this:
function post (root, args) {
// axios
return axios.get(`http://SOME_URL/posts/${args.id}`)
.then(res => res.data);
// fetch
return fetch(`http://SOME_URL/posts/${args.id}`)
.then(res => res.json());
// request-promise-native
return request({
uri: `http://SOME_URL/posts/${args.id}`,
json: true
});
}
The post field has the type Post, so our resolver should return an object with properties like id, title and body. If this is what our API returns, we're all set. However, it's common for the response to actually be an object which contains additional metadata. So the object we actually get back from the endpoint might look something like this:
{
"status": 200,
"result": {
"id": 1,
"title": "My First Post",
"body": "Hello world!"
},
}
In this case, we can't just return the response as-is and expect the default resolver to work correctly, since the object we're returning doesn't have the id , title and body properties we need. Our resolver isn't needs to do something like:
function post (root, args) {
// axios
return axios.get(`http://SOME_URL/posts/${args.id}`)
.then(res => res.data.result);
// fetch
return fetch(`http://SOME_URL/posts/${args.id}`)
.then(res => res.json())
.then(data => data.result);
// request-promise-native
return request({
uri: `http://SOME_URL/posts/${args.id}`,
json: true
})
.then(res => res.result);
}
Note: The above example fetches data from another endpoint; however, this sort of wrapped response is also very common when using a database driver directly (as opposed to using an ORM)! For example, if you're using node-postgres, you'll get a Result object that includes properties like rows, fields, rowCount and command. You'll need to extract the appropriate data from this response before returning it inside your resolver.
Common Scenario #2: Array Instead of Object
What if we fetch a post from the database, our resolver might look something like this:
function post(root, args, context) {
return context.Post.find({ where: { id: args.id } })
}
where Post is some model we're injecting through the context. If we're using sequelize, we might call findAll. mongoose and typeorm have find. What these methods have in common is that while they allow us to specify a WHERE condition, the Promises they return still resolve to an array instead of a single object. While there's probably only one post in your database with a particular ID, it's still wrapped in an array when you call one of these methods. Because an Array is still an Object, GraphQL will not resolve the post field as null. But it will resolve all of the child fields as null because it won't be able to find the appropriately named properties on the array.
You can easily fix this scenario by just grabbing the first item in the array and returning that in your resolver:
function post(root, args, context) {
return context.Post.find({ where: { id: args.id } })
.then(posts => posts[0])
}
If you're fetching data from another API, this is frequently the only option. On the other hand, if you're using an ORM, there's often a different method that you can use (like findOne) that will explicitly return only a single row from the DB (or null if it doesn't exist).
function post(root, args, context) {
return context.Post.findOne({ where: { id: args.id } })
}
A special note on INSERT and UPDATE calls: We often expect methods that insert or update a row or model instance to return the inserted or updated row. Often they do, but some methods don't. For example, sequelize's upsert method resolves to a boolean, or tuple of the the upserted record and a boolean (if the returning option is set to true). mongoose's findOneAndUpdate resolves to an object with a value property that contains the modified row. Consult your ORM's documentation and parse the result appropriately before returning it inside your resolver.
Common Scenario #3: Object Instead of Array
In our schema, the posts field's type is a List of Posts, which means its resolver needs to return an Array of objects (or a Promise that resolves to one). We might fetch the posts like this:
function posts (root, args) {
return fetch('http://SOME_URL/posts')
.then(res => res.json())
}
However, the actual response from our API might be an object that wraps the the array of posts:
{
"count": 10,
"next": "http://SOME_URL/posts/?page=2",
"previous": null,
"results": [
{
"id": 1,
"title": "My First Post",
"body" "Hello World!"
},
...
]
}
We can't return this object in our resolver because GraphQL is expecting an Array. If we do, the field will resolve to null and we'll see an error included in our response like:
Expected Iterable, but did not find one for field Query.posts.
Unlike the two scenarios above, in this case GraphQL is able to explicitly check the type of the value we return in our resolver and will throw if it's not an Iterable like an Array.
Like we discussed in the first scenario, in order to fix this error, we have to transform the response into the appropriate shape, for example:
function posts (root, args) {
return fetch('http://SOME_URL/posts')
.then(res => res.json())
.then(data => data.results)
}
Not Using Promises Correctly
GraphQL.js makes use of the Promise API under the hood. As such, a resolver can return some value (like { id: 1, title: 'Hello!' }) or it can return a Promise that will resolve to that value. For fields that have a List type, you may also return an array of Promises. If a Promise rejects, that field will return null and the appropriate error will be added to the errors array in the response. If a field has an Object type, the value the Promise resolves to is what will be passed down as the parent value to the resolvers of any child fields.
A Promise is an "object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value." The next few scenarios outline some common pitfalls encountered when dealing with Promises inside resolvers. However, if you're not familiar with Promises and the newer async/await syntax, it's highly recommended you spend some time reading up on the fundamentals.
Note: the next few examples refer to a getPost function. The implementation details of this function are not important -- it's just a function that returns a Promise, which will resolve to a post object.
Common Scenario #4: Not Returning a Value
A working resolver for the post field might looks like this:
function post(root, args) {
return getPost(args.id)
}
getPosts returns a Promise and we're returning that Promise. Whatever that Promise resolves to will become the value our field resolves to. Looking good!
But what happens if we do this:
function post(root, args) {
getPost(args.id)
}
We're still creating a Promise that will resolve to a post. However, we're not returning the Promise, so GraphQL is not aware of it and it will not wait for it to resolve. In JavaScript functions without an explicit return statement implicitly return undefined. So our function creates a Promise and then immediately returns undefined, causing GraphQL to return null for the field.
If the Promise returned by getPost rejects, we won't see any error listed in our response either -- because we didn't return the Promise, the underlying code doesn't care about whether it resolves or rejects. In fact, if the Promise rejects, you'll see an
UnhandledPromiseRejectionWarning in your server console.
Fixing this issue is simple -- just add the return.
Common Scenario #5: Not chaining Promises correctly
You decide to log the result of your call to getPost, so you change your resolver to look something like this:
function post(root, args) {
return getPost(args.id)
.then(post => {
console.log(post)
})
}
When you run your query, you see the result logged in your console, but GraphQL resolves the field to null. Why?
When we call then on a Promise, we're effectively taking the value the Promise resolved to and returning a new Promise. You can think of it kind of like Array.map except for Promises. then can return a value, or another Promise. In either case, what's returned inside of then is "chained" onto the original Promise. Multiple Promises can be chained together like this by using multiple thens. Each Promise in the chain is resolved in sequence, and the final value is what's effectively resolved as the value of the original Promise.
In our example above, we returned nothing inside of the then, so the Promise resolved to undefined, which GraphQL converted to a null. To fix this, we have to return the posts:
function post(root, args) {
return getPost(args.id)
.then(post => {
console.log(post)
return post // <----
})
}
If you have multiple Promises you need to resolve inside your resolver, you have to chain them correctly by using then and returning the correct value. For example, if we need to call two other asynchronous functions (getFoo and getBar) before we can call getPost, we can do:
function post(root, args) {
return getFoo()
.then(foo => {
// Do something with foo
return getBar() // return next Promise in the chain
})
.then(bar => {
// Do something with bar
return getPost(args.id) // return next Promise in the chain
})
Pro tip: If you're struggling with correctly chaining Promises, you may find async/await syntax to be cleaner and easier to work with.
Common Scenario #6
Before Promises, the standard way to handle asynchronous code was to use callbacks, or functions that would be called once the asynchronous work was completed. We might, for example, call mongoose's findOne method like this:
function post(root, args) {
return Post.findOne({ where: { id: args.id } }, function (err, post) {
return post
})
The problem here is two-fold. One, a value that's returned inside a callback isn't used for anything (i.e. it's not passed to the underlying code in any way). Two, when we use a callback, Post.findOne doesn't return a Promise; it just returns undefined. In this example, our callback will be called, and if we log the value of post we'll see whatever was returned from the database. However, because we didn't use a Promise, GraphQL doesn't wait for this callback to complete -- it takes the return value (undefined) and uses that.
Most more popular libraries, including mongoose support Promises out of the box. Those that don't frequently have complimentary "wrapper" libraries that add this functionality. When working with GraphQL resolvers, you should avoid using methods that utilize a callback, and instead use ones that return Promises.
Pro tip: Libraries that support both callbacks and Promises frequently overload their functions in such a way that if a callback is not provided, the function will return a Promise. Check the library's documentation for details.
If you absolutely have to use a callback, you can also wrap the callback in a Promise:
function post(root, args) {
return new Promise((resolve, reject) => {
Post.findOne({ where: { id: args.id } }, function (err, post) {
if (err) {
reject(err)
} else {
resolve(post)
}
})
})
I had the same issue on Nest.js.
If you like to solve the issue. You can add {nullable: true} option to your #Query decorator.
Here's an example.
#Resolver(of => Team)
export class TeamResolver {
constructor(
private readonly teamService: TeamService,
private readonly memberService: MemberService,
) {}
#Query(returns => Team, { name: 'team', nullable: true })
#UseGuards(GqlAuthGuard)
async get(#Args('id') id: string) {
return this.teamService.findOne(id);
}
}
Then, you can return null object for query.
Coming from Flutter here.
I couldn't find any flutter related solution to this so since my search always brought me here, lemme just add it here.
The exact error was:
Failure performing sync query to AppSync:
[GraphQLResponse.Error{message='Cannot return null for non-nullable
type: 'AWSTimestamp' within parent
So, in my schema (on the AppSync console) I had this:
type TypeName {
id: ID!
...
_version: Int!
_deleted: Boolean
_lastChangedAt: AWSTimestamp!
createdAt: AWSDateTime!
updatedAt: AWSDateTime!
}
I got the error from the field _lastChangedAt as AWSTimestamp couldn't be null.
All I had to do was remove the null-check (!) from the field and it was resolved.
Now, I don't know the implications of this in the long run but I'll update this answer if necessary.
EDIT: The implication of this as I have found out is anything I do, amplify.push that change is reversed. Just go back to your appsync console and change it again while you test. So this isn't a sustainable solution but chatter I've picked up online suggests improvements are coming to amplify flutter very soon.
#Thomas Hennes got it spot on for me
The title field was resolved even though we didn't provide a resolver for it because the default resolver did the heavy lifting -- it saw there was a property named title on the Object the parent field (in this case post) resolved to and so it just resolved to that property's value. The id field resolved to null because the object we returned in our post resolver did not have an id property. The body field also resolved to null because of a typo -- we have a property called bod instead of body!
Pro tip: If bod is not a typo but what an API or database actually returns, we can always write a resolver for the body field to match our schema. For example: (parent) => parent.bod
One important thing to keep in mind is that in JavaScript, almost everything is an Object. So if the post field resolves to a String or a Number, the default resolver for each of the fields on the Post type will still try to find an appropriately named property on the parent object, inevitably fail and return null. If a field has an object type but you return something other than object in its resolver (like a String or an Array), you will not see any error about the type mismatch but the child fields for that field will inevitably resolve to null.
In case anyone has used apollo-server-express and getting null value.
// This will return values, as you expect.
const typeDefs = require('./schema');
const resolvers = require('./resolver');
const server = new ApolloServer({typeDefs,resolvers});
// This will return null, since ApolloServer constructor is not using correct properties.
const withDifferentVarNameSchema = require('./schema');
const withDifferentVarNameResolver= require('./resolver');
const server = new ApolloServer({withDifferentVarNameSchema,withDifferentVarNameResolver});
Note: While creating an instance of Apolloserver pass the typeDefs and resolvers var name only.
If none of the above helped, and you have a global interceptor that envelopes all the responses for example inside a "data" field, you must disable this for graphql other wise graphql resolvers convert to null.
This is what I did to the interceptor on my case:
intercept(
context: ExecutionContext,
next: CallHandler,
): Observable<Response<T>> {
if (context['contextType'] === 'graphql') return next.handle();
return next
.handle()
.pipe(map(data => {
return {
data: isObject(data) ? this.transformResponse(data) : data
};
}));
}

Firebase Cloud Functions: Transactions function not returning promise?

here is what I am trying to do with firebase cloud function:
-Listen to any change in one of the documents under 'user' collection.
-Update carbon copies of the userinfo in the relevant documents in both 'comment' and 'post' collections.
Because I will need to query in relevant documents and update them at once, I am writing codes for transaction operations.
Here is the code that I wrote. It returns the error message, 'Function returned undefined, expected Promise or value'.
exports.useInfoUpdate = functions.firestore.document('user/{userid}').onUpdate((change,context) => {
const olduserinfo=change.before.data();
const newuserinfo=change.after.data();
db.runTransaction(t=>{
return t.get(db.collection('comment').where('userinfo','==',olduserinfo))
.then((querysnapshot)=>{
querysnapshot.forEach((doc)=>{
doc.ref.update({userinfo:newuserinfo})
})
})
})
.then(()=>{
db.runTransaction(t=>{
return t.get(db.collection('post').where('userinfo','==',olduserinfo))
.then((querysnapshot)=>{
querysnapshot.forEach((doc)=>{
doc.ref.update({userinfo:newuserinfo})
})
})
})
})
});
I am a bit confused because as far as I know, 'update' method returns a promise? I might be missing something big but I picked up programming only last November, so don't be too harsh. :)
Any advice on how to fix this issue? Thanks!
EDIT:
Building on Renaud's excellent answer, I created the below code in case someone may need it.
The complication with transaction is that the same data may be stored under different indices or in different formats. e.g. The same 'map' variable can be stored under an index in one collection, and as part of an array in another. In this case, each document returned by querying needs different update methods.
I resolved this issue using doc.ref.path, split, and switch methods. This enables application of different update methods based on the collection name. In a nutshell, something like this:
return db.runTransaction(t => {
return t.getAll(...refs)
.then(docs => {
docs.forEach(doc => {
switch (doc.ref.path.split('/')[0]) { //This returns the collection name and switch method assigns a relevant operation to be done.
case 'A':
t = t.update(doc.ref, **do whatever is needed for this collection**)
break;
case 'B':
t = t.update(doc.ref, **do whatever is needed for this collection**)
break;
default:
t = t.update(doc.ref, **do whatever is needed for this collection**)
}
})
})
})
Hope this helps!
Preamble: This is a very interesting use case!!
The problem identified by the error message comes from the fact that you don't return the Promise returned by the runTransaction() method. However there are several other problems in your code.
With the Node.js Server SDK you can indeed pass a query to the transaction's get() method (you cannot with the JavaScript SDK). However, in your case you want to update the documents returned by two queries. You cannot call twice db.runTransaction() because, then, it is not a unique transaction anymore.
So you need to use the getAll() method by passing an unpacked array of DocumentReferences. (Again, note that this getAll() method is only available in the Node.js Server SDK and not in the JavaScript SDK).
The following code will do the trick.
We run the two queries and transform the result in one array of DocumentReferences. Then we call the runTransaction() method and use the spread operator to unpack the array of DocumentReferences and pass it to the getAll() method.
Then we loop over the docs and we chain the calls to the transaction's update() method, since it returns the transaction.
However note that, with this approach, if the results of one of the two original queries change during the transaction, any new or removed documents will not be seen by the transaction.
exports.useInfoUpdate = functions.firestore.document('user/{userid}').onUpdate((change, context) => {
const olduserinfo = change.before.data();
const newuserinfo = change.after.data();
const db = admin.firestore();
const q1 = db.collection('comment').where('userinfo', '==', olduserinfo); // See the remark below: you probably need to use a document field here (e.g. olduserinfo.userinfo)
const q2 = db.collection('post').where('userinfo', '==', olduserinfo);
return Promise.all([q1.get(), q2.get()])
.then(results => {
refs = [];
results.forEach(querySnapshot => {
querySnapshot.forEach(documentSnapshot => {
refs.push(documentSnapshot.ref);
})
});
return db.runTransaction(t => {
return t.getAll(...refs)
.then(docs => {
docs.forEach(doc => {
t = t.update(doc.ref, { userinfo: newuserinfo })
})
})
})
})
});
Two last remarks:
I am not sure that db.collection('comment').where('userinfo', '==', olduserinfo); will be valid as olduserinfo is obtained through change.before.data(). You probably need to specify one field. This is probably the same for newuserinfo.
Note that you cannot do doc.ref.update() in a transaction, you need to call the transaction's update() method, not the one of a DocumentReference.

Proper node.js abstractions to prevent race conditions when accessing ethereum blockchain

I am using web3 version 1.0.0-beta.27 where all accesses to the blockchain will be asynchronous, clearly this opens up the possibility of race conditions, ie:
var Web3 = require("web3");
// connect to etherum blockchain
var ether_port = 'http://localhost:8545'
var web3 = new Web3(new Web3.providers.HttpProvider(ether_port));
// this is how we set the value, note there is the possiblity of race condidtions here
var accounts = []
web3.eth.getAccounts().then(function(accts){
console.log("printing account: ", accts)
accounts = accts
})
// observe race condition
console.log("assert race condition: ", accounts[0])
The last line above is contrived, it is there to demonstrate that I would like to use accounts after it has been evaluated. Ie, eventually I would like modify/read the blockchain from a front end express.js web app or even a mobile app, so in the interest of being rigorous, what are the common tools in node.js to ensure race conditions never occur? Do these tools exist? If not what are some common practices. I am new to node.js as well.
One idea is to not attempt to directly store the data because code trying to access the data has no idea when it's valid due to the uncertain nature of asynchronous results. So, instead you store the promise and any code that wants access to the data, just uses .then()/.catch() on the promise. This will always work, regardless of the async timing. If the data is already there, the .then() handler will be called quickly. If the data is not yet there, then the caller will be in line to be notified when the data arrives.
let accountDataPromise = web3.eth.getAccounts().then(function(accts){
console.log("printing account: ", accts)
return accts;
});
// then, elsewhere in the code
accountDataPromise.then(accts => {
// use accts here
}).catch(err => {
// error getting accts data
});
FYI, assigning data from a .then() handler to a higher scoped variable that you want to generally use in other code outside the promise chain is nearly always a sign of troublesome code - don't do it. This is because other code outside the promise chain has no idea when that data will or will not be valid.

How to update a property of an object using Parse Cloud Code?

Every Parse Installation object instance in my Parse database has a pointer to a specific user. I have a background job that runs for every user, and what I want to do in this part of the background job is to set the respective user Installation's channel property to ["yesPush"], for push notification targeting purposes.
The way I figured I would do it is by querying for the specific Parse.Installation instance, and then setting its channels property. This doesn't seem to be working however. I'm trying to follow the guidelines in the Parse Cloud Code Docs, but it's either not the correct use case, or I'm not following it correctly.
Code:
var installationQuery = new Parse.Query(Parse.Installation);
installationQuery.equalTo('userId', parentUser);
installationQuery.find().then(function(results) {
return Parse.Object.set('channels', ["yesPush"]);
});
The way I would do it is as follows:
// for every User
var userQuery = new Parse.Query(Parse.User);
userQuery.each(function(user) {
var installationQuery = new Parse.Query(Parse.Installation);
installationQuery.equalTo('userId', user);
return installationQuery.first().then(function(installation) {
installation.set('channels', ['yesPush']);
return installation.save();
});
}).then(function() {
status.success();
}, function(error) {
status.error(error.message);
});
The each() function is how you process large sets of data in a job. If you are performing other async tasks inside it you need to return their promise.
The first() function is much faster and easier if we only expect one record.
I am calling set() on the actual installation object returned by first().
I am returning the save() promise to allow promise chaining.

return $add ref of Firebase item AngularFire

Let's say I have a collection of items:
var itemsRef = new Firebase("https://example.firebaseio.com/items");
$scope.items = $firebase(itemsRef);
And we $add an item:
$scope.items.$add($scope.item);
I understand the ref gets generated client side before making it to the Firebase collection.
How do I get that ref after adding the item? For example -Jx8363hdu12
AngularFire 0.6.0
As of AngularFire 0.6.0 $add, $save, $set and $remove use promises:
https://github.com/firebase/angularFire/issues/183
$scope.items.$add($scope.item).then(function(p){
console.log(p.name());
});
For others coming by here if you had code that previously worked using
var bleh = $scope.items.$add($scope.item);
Previously $add would return the actual value, but as Dan mentioned above it was changed to return a promise.
You have two options (the later being the better).
Move back to an older version of angularfire.
You will HAVE to use the .then operation.
I have had this problem a few times and keep running into it (i'm hoping the more variations on the term can be found the more likely if it happens again to me or others it'll be easier to find).
I had it in my head that a promise meant that you could still use the variable and at some point in the future it would fill it in (so I kept thinking that it would fill it in eventually and was getting annoyed that it never seemed to).
From here: http://www.html5rocks.com/en/tutorials/es6/promises/
Here's how you use that promise:
promise.then(function(result) {
console.log(result); // "Stuff worked!"
}, function(err) {
console.log(err); // Error: "It broke"
});
"then" takes two arguments, a callback for a success case, and another for the failure case. Both are optional, so you can add a callback for the success or failure case only.
So in theory if firebase errors out saving the data (adding/removing/etc) you should at least have the error function so you can trap that something wrong has happened.
For Dan's example:
$scope.items.$add($scope.item).then(
function(p){
console.log(p.name());
},
function(err){
console.log("The expected Firebase action failed to occur this was your error: " + err);
});

Categories