I want to pass the previously resolved, returned data and an additional parameter within a promise chain. See the example for clarification.
Below functions both return a Promise and are properly executed. It's really just about passing additional parameter.
Lets consider a Promise chain like:
API.getSomething(id).then(API.processIt)
getSomething function(id) { returns a promise with data }
processIt function(data) { process the returned data }
With a syntax like above it works fine. Once I add additional parameter:
API.getSomething(id).then(API.processIt(data, "random"))
processIt function(data, misc) {...} it does't work anymore.
Is there a way to pass additional parameters within a Promise chain using the result of the previous executed Promise without any additional library?
It's not about the design of the whole chain. I know, the problem could be bypassed with a different design but due to changes in some APIs that's the way I have to handle with the problem.
On this line
API.getSomething(id).then(API.processIt(data, "random"))
You are trying to pass function as reference but you are invoking the function instead.
Try
API.getSomething(id).then(function(data){
API.processIt(data, "random");
});
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 just learned about promises and async/await.
I want my function to wait for some function inside to finish before proceeding.
Basically, I guess it should look something like this:
async function doSomething(data){
//some code
await createMarkup(data)
//do some stuff which must wait for createMarkup to finish
}
function createMarkup(input){
return new Promise ((???) => {
//some code
resolve(markup)
})
}
Now, in most of the tutorials I read about promises and stuff, the parameter of the "new Promise" was always "(resolve, reject)". This has been the case so often that I wondered whether this is some necessity?
In my case, the promise shall take exactly one argument. So can I just, like in any other parameter, put my one argument into the parameter and thats it? Or do I have to take care of somethign?^^
In my case, the promise shall take exactly one argument.
Promise will take one argument. That argument will be the function you want it to run. This is how Promise is defined. It is not something under your control.
The function you pass to the promise will receive two arguments. It is passed them when it is called, which is done by the Promise library (which is not code you wrote, and follows the specification for Promises, so it is not something under your control). It is traditional to call them resolve and reject, but you can call them whatever you like. The function you pass needs to call resolve(any_data) if it succeeds and reject(any_data) if it fails. If you don't intend to call reject, then you don't need to mention it in the argument list, the second argument will be passed to the function though.
You can create a function which returns a promise (like createMarkup in your example), which takes any arguments you like and makes them available to the function you pass to Promise via closures.
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.
In my controller, I use a method from a factory to update some data. For example, I'm trying to fetch an updated array of users. Should I be returning the promise itself from the factory? Or should I be returning the data from the promise (not sure if I phrased that correctly)?
I ask because I've seen it both ways, and some people say that the controller shouldn't have to handle whether the request was successful or if it failed. I'm specifically talking about the promise returned from $http in this case.
Or maybe in other words, should I be using the then() method inside the factory, or should I be using it in the controller after returning from the factory?
I've tried to handle the success and error callbacks (using the this() method) from within the service, but when I return the data to the controller, the users array is not properly updated. I'm assuming that's because of the request being async. So in the controller, it would look something like this:
vm.users = userFactory.getUsers();
If I handle the promise from within the controller, and set the users array within the then() method, it works fine. But this goes back to where I should be using then():
userFactory.getUsers().then(
function(data){
vm.users = data;
}, ...
Hopefully someone would be able to shed some light on this or provide some input. Thanks!
There's no way you can return the data from the factory (since it's an async call) without using either a callback approach (discouraged):
userFactory.prototype.getUsers = function(callback){
$http.get('users').then(function (response) {
callback(response.data);
});
};
Or the promise approach.
If you're worried about handling the errors on the controller, then worry not! You can handle errors on the service:
userFactory.prototype.getUsers = function(){
return $http.get('users').then(function(response) {
return response.data;
}, function(error) {
// Handle your error here
return [];
});
};
You can return the results of then and it will be chained. So things from service will execute and then, later on, Controller ones.
I have no problem with controller deciding what to do basing on response failing/succeding. In fact it lets you easily handle different cases and doesn't add a lot of overhead to the controller (controller should be as small as possible and focused on current task, but for me going different path whether request failed is the part of its task).
Anyway, in Angular HTTP requests are wrapped in promises internally (I remember that in the previous versions there was a way to automatically unwrap them), so returning from service/factory always returns a promise, which has to be resolved.
I prefer returning a promise from a service/factory because I tend to let other classes decide what to do with the response.
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).