Just started to use Hood.ie for a web app, however am facing issues in obtaining some data.
I want to get the data and then simply do something like
hoodie.store.find('teammember', theId).firstName;
Is this possible?
Thanks.
What you are looking for is
hoodie.store.find('teammember', theId)
.done(function(object) { object.firstName })
.fail(function(error) { alert(error.message) })
Most methods of Hoodie are asynchronous and return promises. A promise is an object with methods to which you can pass callback function. By standard, a Promise has .then & .catch methods, Hoodie also adds .done & .fail. .done(callback) gets called when the method succeeded. .fail(callback) gets called when it failed. .then(callback) and .catch(callback) additionally allow to chain the callbacks.
Find more information on Promises here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise And a great article on common gotchas here: http://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html
Related
I have a Dialog object that will show, well, dialogs. There are many entry points to show dialogs, e.g. yesNo(), message(), confirm(), etc. However, all these methods basically call the same other method, called showSimpleDialog(title, message, buttons).
I'd like all these methods (showSimpleDialog too) to return a promise, but there's a snag:
yesNo() {
return new Promise((resolve, reject) => {
axios
.get(......)
.then(this.showSimpleDialog(...));
}
}
As you can see, I am prevented in the above example from either returning the promise that showSimpleDialog would make or by passing the instanced Promise to showSimpleDialog.
The former is impossible because we're already in a different Promise by the time we have access to it. The latter because the Promise object itself is not yet available within the constructor. Well, technically, in this particular case it is (exactly because we're already in a different Promise), but some of my entry functions are synchronous, some asynchronous and I simply can't use the same code pattern to achieve the same effect in both cases.
I investigated the thing and I found this, but the author suggests the approach is flawed and archaic to begin with.
So, what would be the correct approach to return a functioning Promise from ALL entry points while the entry points would still be free to reusing each other's Promises?
If I understand correctly, this.showSimpleDialog(...) also returns a Promise, right?
If you want yesNo() to return the Promise retunred by this.showSimpleDialog(...)
yesNo() {
return axios
.get(......)
.then(()=>{
return this.showSimpleDialog(...);
});
}
That being said, consider using async/await, especially when dealing with multiple sequential promises, if possible.
Your code is calling this.showSimpleDialog immediately (synchronously) without waiting for any promise to resolve (the axios one). This is because the code doesn't pass a function to the then method, but instead executes this.showSimpleDialog. This execution returns a promise (presumably), but then expects a function as argument, not a promise.
So you need to make sure to pass a callback to then, and let that callback return a promise. This way promises will be chained:
.then(() => this.showSimpleDialog(...));
It is also important to make that callback an arrow function, since you'll be referencing this, which is intended to be the this on which yesNo is called.
I'm not so familiar with promises.
I would like hide promise-implementation from promise-call.
Example:
function findFriends(req, res) {
const promiseFriend = MyFriendes.find({}).exec(); //call promise
if(friends.length===0){
logger.warn('No friendsavailible');
}else if(friends === undefined){
res.status(500).json({
error: 'INTERNAL ERROR'
});
}else{
res.status(200).json({
friends: friends
});
}
}
and I will resolve my promise within same file but not
at same function, where I call this promise.
promiseFriend
.then(function(friends){
return friends;
})
.catch(function(err){
logger.error({error:err});
});
Now, I get, that "promiseFriend" is undefined.
How can I separate promise-call from promise-resolution?
If you want to define a promise in a function and use it somewhere else then first of all you need to return the promise from that function, which you're not doing in your code. Then you need to actually call that function which you are also not doing. And finally you need to use a then callback on the returned value, which you are not doing in this case as well.
There is no point in saving the promise in a local variable promiseFriend that is scoped to this function. There is also no point to return a value in your then callback: .then(function (friends) { return friends; }) - I have no idea what have tried to do here.
I suppose that findFriends is supposed to be a route handler for Express. If so then make sure that you send a response in every case (which you don't do for friends.length===0). Also, you need to actually add a then handler to the saved promise if you want to act when it's resolved. Right now you don't even have friends defined in your function. Also add a catch handlers and also send a response for that case.
Then you might return the promise from your function but not if it is a route handler, it doesn't make sense. You can return a promise from a function:
function x() {
return MyFriendes.find({}).exec();
}
and then use it:
x().then(friends => ...).catch(error => ...);
but you cannot use return values if you don't return it, you can't use undefined variables as if they were defined, and you actually need to consider who is your return value returned to.
I suggest that you learn how Node actually works because it seems that you have copied and pasted some random code, joined it together and expect that it does what you want without actually trying to understand it.
To get a better understanding on the asynchronous nature of Node that is giving this execution order here, see those answers:
A detailed explanation on how to use callbacks and promises
Explanation on how to use promises in complex request handlers
An explanation of what a promise really is, on the example of AJAX requests
An explanation of callbacks, promises and how to access data returned asynchronously
Don't try to write Node programs before you understand the concept of function calls, return values, callbacks and in this case promises.
I am making an ajax call to server to fetch some data.
$.ajax(
{
url: "myserver",
method: "GET",
}.success(function(data)
{ }
.error(function(e)
{ }
)
I have been reading about .then().
Is there any performance benefit of using .then() over .success()?
Is there any particular scenario where I should use .then() and .success()?
Plus, whoever answers,please brief me in short What is Promises.
You should be using then as the success and error have been deprecated.
https://docs.angularjs.org/api/ng/service/$http
The $http legacy promise methods success and error have been
deprecated. Use the standard then method instead. If
$httpProvider.useLegacyPromiseExtensions is set to false then these
methods will throw $http/legacy error.
.then( ) call returns a promise while .success( ) is more traditional way of registering callbacks and it doesn't return a promise.
Moreover .then() is commonly used where you need to chain promises whereas .success() method is a streamlined, convenience method when you don't need to chain call nor work with the promise API.
I would recommend using .then() and .catch(). Those methods are in line with the CommonJS standard. As you use other Promise libraries, it's more likely that they'll use those two methods.
I would also avoid using the .then(successCallback, failureCallback) approach, as it is not standard and less obvious.
This is a great article which helps you to understand Promise
http://andyshora.com/promises-angularjs-explained-as-cartoon.html
and
The major difference between the 2 is that .then() call returns a promise (resolved with a value returned from a callback) while .success() is more traditional way of registering callbacks and doesn't return a promise.
I personally prefer .then(), here is a very good blog on why .success() is not preferred.
For an API call I would do something like this:
$http.get('www.domain.com/someAPI').then(function (results) {
// On successful promise
doSomethingHere();
}, function (error) {
// On failed promise
handleError();
});
.Success and .then both work same but there are lot of difference between there response unit, In angular and ajax success work same after evening thing goes completed and you might need to fetch response data then User .success,
In .then it happens before .Success and After .Success.
so if You have Loading bar in your html code use before success .then for loading...
and after success use .then for hiding it.
Ive been trying to find the simplest JavaScript promise(without libraries) so i can get it into my thick skull. Thought i was getting the concept, but seem to be unable to work it. Can anyone fix this?
function fetch(message){
return message;
}
var promise = fetch('beep')
promise.then(function(dMessage){
console.log(dMessage);
}).catch(function(err){
console.error('error-', err);
})
ERROR Message:promise.then is not a function
Am also a little confused about when i can use this? NodeJs will be able to use this without extra libraries right? for client side i should get ES6-promise?
Solution underneath with thanks to Daniel B
function fetch(message){
return new Promise(function(resolve, reject){
resolve(message);
});
}
fetch('word').then(function(dMess){
console.log(dMess);
}).catch(function(err){
console.error('error-', err);
})
You are overwriting the native fetch function. Simply remove your function and it will work.
If you want to define your own fetch function, it has to return a promise, as below.
function fetch(message){
return Promise.resolve(message);
}
I don't believe the other answer is correct. Although it's correct in 'fetch' is a method native to browsers (not javascript which the user implied) it is not the reason why your promise doesn't work, and doesn't explain what you're not understanding about promises.
The first 'promise' in a chain always has to be a promise constructor/instance. You can create these in many ways, but if you have only a simple value like a string, you must wrap it in Promise.resolve(string). Afterwords, and other promises in the chain won't need this functionality as they are all wrapped in the top level promise of the chain. At least this is how most implementations like Q/Bluebird/ES6 Native promises will work.
I am writing an asynchronous javascript function that will be called by consumers to get certain data. Following is the simple implementation that I wrote initially (error handing and other stuff removed for clarity).
function getData(callback){
if (data is available as a JavaScript object){
callback(data);
}else{
getAsyncData(function(data){
//some transformations on data
callback(data);
});
}
}
What is important to note is that getData can return data quickly if data is already available as a JavaScript object.
I want to replace this implementation with the one that returns a promise object to the caller. This fiddle shows sample implementation - http://fiddle.jshell.net/ZjUg3/44/
The question - Since getData can return quickly, can there be a possiblity where getData is resolving the promise even before caller has established handler chain using then method? Just to simulate this, in the fiddle if i call then method inside setTimeout function (with zero delay), callback doesn't get called. If i call the then method outside of the setTimeout function, callback gets called. I am not sure if this is even a valid concern or valid usecase. I am quite new to angularjs development and would appreciate your views :)
If you want getData() to return a $q promise instead of using a callback, I'd do the following refactor using $q.when() and usual $q.resolve():
function getData()
{
if (data is available as a JavaScript object) {
return $q.when(data); // resolves immediately
} else {
var q = $q.defer();
getAsyncData(function(data){
//some transformations on data
q.resolve(data);
});
return q.promise;
}
}
No, a significant and important part of being a promise is that it doesn't matter when you attach the handler. Even if you create a promise now and resolve it immediately, then keep your computer running for the next 50 years, then attach a handler it will still fire.
All of this does assume that there isn't a bug/corner case in angularjs's promise implementation. If it doesn't work, it's a bug though.
If you ever need to know anything about how promises work, you can always refer to the Promises/A+ spec which angular adheers to. As a spec, it's one of the simplest and easiest to understand that I've come across (although I should mention that I've been involved in the spec for quite a while now).