How to get this javascript promise to work - javascript

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.

Related

How to properly return a value from a callback within a Promise?

I know that very similar questions have been asked, but I can't find one that fits my issue exactly- feel free to point me that way if there is one.
sendSteamAuthTicket: () => {
return new Promise((resolve, reject) => {
greenworks.getAuthSessionTicket(function(ticket) {
console.log('Successfully retrieved Steam API User Auth Ticket.')
console.log(ticket.ticket.toString('hex'))
resolve(ticket.ticket.toString('hex'))
}, function(e) { throw e })
})
}
Basically, this returns an endlessly pending Promise, leading me to believe I can't resolve a Promise from within a nested callback like this. Unfortunately, I can't send the data via an additional function because electron won't let you interface with the browser that way.
Is it possible to do what I'm trying to do here? e.g. more or less obtain a delayed Promise value within this single function?
Alright, I figured it out- sorry for the redundant question, I've been banging my head on this for a few hours. Hearing that the Promise syntax was correct was apparently enough to get it through.
The greenworks package was being imported incorrectly (or, rather, correctly- according to their docs- but needed a direct file path)
It's a little outdated so I wasn't sure why at first.
There's nothing wrong with the way that you're calling resolve. If the callback is called, resolve will be, too, unless ticket is null or similar. My guess would be that greenworks is calling the error callback and then not re-throwing your thrown error. Try doing reject(e) instead of throw e.

Reusing an existing Promise object if exists

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.

Promise not working in chain of javascript /jquery functions

I have a series of async functions that i want to execute in a sequence, i tryed using promises but the exmple i followed tho it works, does not execute then in orther, and many times one resolves the content, before the other draws the container. i have tryed to understand the promises thing and it seems that the promises is being rejected, but i dont know what im doing wrong, or if i should use other method to "chaing" the functions. Thanks for the help!
var chain = new Promise(function(){
statusUp();
});
chain.then(p_view(pid)).then(pu_list(pid)).then(pm_list(pid));
You're looking for something similar to this
Promise.resolve(statusUp())
.then(function(pid) {
return p_view(pid)
})
.then(function(pid) {
return pu_list(pid)
})
.then(function(pid) {
return pm_list(pid)
});
I made some (a lot of...) assumptions here regarding statusUp, p_view, pu_list and pm_list so this might need some tweaking.

AngularJs promises: can you use both success and then?

I feel this is a very bad idea as i do not find it anywhere but testing it on my localhost it seems to work. I have a service :
angular
.module('trips.services')
.service('Trip', Trip);
function Trip($http, $q) {
//.....
function create(data) {
var api_url = "/api/trip";
return $http.post(api_url, data).success(function(data) {
mixpanel.track("Trip: created", {}); // track that a new event happened
});
}
}
I also have a controller where i do something like:
Trip.create(data).success(function(data) {
//do something after the trip is created
})
Now as you can see in this example I use both the then promise and the success callback in the service. If i do breakpoints in the debugger the success callback from the service is executed first and then the then clause from the controller. And it is also great for code organization, the common things i do after the service is successful is in the service while the specific things are in the controller. The thing is, i feel it is very non-according to any documentation or examples. Did not really find it somewhere, I discovered it by mistake. It might not work in some cases also?
I know the other options also, the $q library and could deffer in the service but that ends up in much more code.
So, is this a bad idea and why? Any opinions would be very helpful. I do not want to set up a wrong practice.
Using promises consequently is considered a good practice as you already know. To do that, you can simply replace your success-callback with another then:
function create(data) {
var api_url = "/api/trip";
var promise = $http.post(api_url, data);
promise.then(function(data) {
mixpanel.track("Trip: created", {}); // track that a new event happened
});
return promise;
}
Having multiple independent .then()s on one promise is perfectly fine and works as you would expect.
It's not necessarily a bad idea, it's just you using chaining of promises.
The .then function looks like this:
.then(function(success){}, function(error){});
you can see that .success is just shorthand for the first function above (as if you didn't declare the error callback).
Seeing as the promise can be passed around or maybe you have multiple services making the same request and you want just one promise created, then you might like to declare callbacks from multiple areas yet have just one promise resolve.
So is it a bad idea? No. Why? It is a flexible piece of code which is really up to the programmer to use. Can you declare multiple thens? Yes. Should you mix it with success callbacks? You can, but you might just want to stick to one style for consistency. But thats really up to what you're trying to achieve.
Angular documentation: https://docs.angularjs.org/api/ng/service/$http
(Watch out for deprecation, might just want to stick to .then)

Returning angular promise from a function that resolves the promise very quickly

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).

Categories

Resources