How to set variable value with a promise - javascript

I'm stuck figuring how set a variable value (ex. response of an ajax call) using promises.
I have for instance:
something.value = getVariable('id'); // { id : 'Adam Smith' }
where
getVariable(id) {
return $.ajax({
//...
}).done(function(response) {
//... getVariable return response
}).fail(function(response) {
//... getVariable return something_else
});
// ...
getVariable should change from promise to ajax (or any other asynchronous) response value once done().

You can't directly set a variable the way you're trying to do it. Because your operations are async, the only place you can reliably use the result of your async operations is inside the promise handlers such as .done() or .then(). So, setting the result into some variable and then expecting to use that variable in other code usually won't work properly. It will usually result in timing issues.
Instead, you have to learn to program with asynchronous results where you actually USE the variable inside the promise handler callback. You don't store it and then expect to use it in other code.
function getVariable(id) {
return $.ajax({...});
});
getVariable(...).then(function(response) {
// process result here
// don't just store it somewhere and expect other code to use that stored
// value. Instead, you use the result here and put whatever code
// needs that value in here.
}, function(err) {
// handle error here
});

Related

ReferenceError message in javascript?

Why am i getting the following error:ReferenceError: result is not defined"
function returnData() {
_myService.getData().then(function(data) {
var result = data;
});
return result;
}
Because result is declared within the callback you passed into then. It doesn't exist outside.
You can declare it outside, but note that it won't have the data as of your return result; line later:
function returnData(){
var result; // <==== Note
_myService.getData().then(function(data){
result = data; // <==== No `var` here
})
// WON'T HAVE THE VALUE HERE, it's too soon
return result;
}
See How do I return the response from an asynchronous call? for why, and what to do about it. Basically, you don't need the returnData function at all, it doesn't add any value (other than perhaps encapsulation around _myService). It cannot return the value. So either use _myService directly, or if you're trying to hide that, just
function returnData() {
return _myService.getData();
}
...and use then in the calling code to receive it. Since again, returnData can't return the data.
#Yosvel's answer is correct, the reason is because you are making an Asynchronous call to your service.
In doing so, you must wait for a result to be returned to you, which can then be processed in your then function.
By having two return calls, your return value is undefined because it is not waiting for the callback function, but simply returning a null value.
I suppose that calling _myService.getData() you are making an Asynchronous call to a web service..
In that case you can return your service response data like this:
function returnData() {
return _myService
.getData()
.then(function(data) {
// Here you can work with the response data
return data;
});
}
Notice that you can work with the response in the callback, as you correctly passed into then.

Not able to return value even with callback function

I have read the following questions and corresponding insightful answers and understood how asynchronous call back functions work-
How do I return the response from an asynchronous call?
How to return value from an asynchronous callback function?
Returning value from asynchronous JavaScript method?
But still not able to successfully return the appropriate vaule. Following is the code -
function foo(callback){
request('some-url.json', function (error, response, body) {
//Check for error
if(error){
//error body
}
//Check for right status code
if(response.statusCode !== 200){
//response body
}
//All is good. Print the data
var data = JSON.parse(body);
callback(data.some-property);
});
}
module.exports = {
foo:foo(function(result){
console.log(result); //works
return result; //doesn't work
}),
};
I am able to get the expected result in the console log but still its not able to return the value.
Error: TypeError: Property 'foo' of object #<Object> is not a function
Problem:
1.Is the callback function execution correct?
2.What should I do to return the value successfully?
Edit: Finally after an extensive conversation with Paarth I have decided to resort to promise.js which will allow me to indirectly return the value I seek from my function. For further resources regarding promise.js -
https://gist.github.com/domenic/3889970
https://www.promisejs.org/
http://colintoh.com/blog/staying-sane-with-asynchronous-programming-promises-and-generators
Also worth mentioning : Bluebird & q
There's no real way to go from asynchronous code back to synchronous code. You can get close by using promises which treat delayed operations as data so you can return the promise object and set up actions that will happen on it later, but with callbacks you have to just keep creating callbacks.
You can find some basic information on promises here https://www.promisejs.org/ (though I'm not endorsing promise.js) and more here.
If you're working in ES5 Bluebird and Q are well known promise libraries. Promises are native functionality in ES6.
So ignoring the module syntax let's say you're trying to use that function.
function something() {
...
// result not bound, foo is not called
foo(function(result){
console.log(result); //result was passed into this callback and is bound
return result; //result is still bound but returning does nothing. No one is waiting for the return value.
});
// code below this point probably already executed before your console.log in the foo callback. No one is waiting for the return.
}
Responding directly to your questions:
Yes, you called foo correctly until you tried to return something. Returning isn't really a concept that applies to callback functions. You can only pass the data on to other callbacks.
You don't ever return the value.
Let's say I have foo, which takes in a callback. If I want to act on foo's result in another function, foo2, I have to call
function foo2 () {
foo(function(result) {
//act on result
}
}
Now let's say I want foo2 to return foo1's result to yet another function. Well, with callbacks, I can't. I can only ask foo2 to take in yet another callback and pass on the data.
function foo2 (callback) {
foo(function(result) {
callback(result);
}
}
That's because module.exports won't wait to the request (asynchronous) to finish. Simply export the function and call it somwhere when you want.
You can export the function :
//yourController.js
module.exports = foo;
Now require that function somewhere in other file and call it :
// another.js
var foo = require('yourController.js');
foo(function(result){
// your result is here
});
Or
require('yourController.js')(function(result){/* Do whatever with result */});

Access the value of a Javascript object

I am working with a function that returns a value to a variable. When i console log the variable it shows what your seen in the image. i need to get access to the value so I can display it to the user how can i do this?
this is my code
function save(user)
{
var response= Restangular.all('admin').post(user).then(function (postedUser) {
return postedUser;
});
console.log(response);
return response;
}
reponse is a promise. You can't (or should not be able to) access the value of a promises directly, since the promise might not be resolved yet.
Instead, you have to pass a callback to the promise. When the promise is resolved with a value, it passes that value to all attached callbacks. In your example, the promise will eventually be resolved with value of postedUser.
The function that calls save can access the value like so:
save(...).then(function(value) {
// do something with value here
});
Learn more about promises.
Note: You can drop the .then inside the function and simplify it to
function save(user) {
return Restangular.all('admin').post(user);
}
since you are passing the identity function to .then.

Does this JavaScript function need to return a Promise?

Let's say I have some JS that makes an AJAX call like this:
$.getJSON(myUrl, { targetState: state }, function (jsonData) {
}).success(function (jsonData) {
...
...
...
});
Now let's assume I want to wrap this code in a function and have it return some value, in the success block, so I can call it from various places in my app. Should the function I create return a Promise? I'm thinking it probably does, but I've never created a JS function that returned a Promise so I'm not entirely certain when I need to do this.
Should the function I create return a Promise
Yes. If you want to use promises, every function that does anything asynchronous should return a promise for its result. No exceptions, really.
wrap this code in a function and have it return some value in the success block
Good news: It's not complicated, as $.getJSON does already give you a promise to work with. Now all you need to do is to use the then method - you can pass a callback to do something with the result and get back a new promise for the return value of the callback. You'd just replace your success with then, and add some returns:
function target(state) {
var myUrl = …;
return $.getJSON(myUrl, { targetState: state })
// ^^^^^^
.then(function (jsonData) {
// ^^^^
/* Do something with jsonData */
return …;
// ^^^^^^
});
}
With promises, you do no more pass a callback to the $.getJSON function any more.
so I can call it from various places in my app
Now, you can call that target function, and get the result of the returned promise in another callback:
target({…}).then(function(result) {
…; return …;
});

Callback returns undefined with chrome.storage.sync.get

I'm building a Chrome extension and I wrote this code.
var Options = function(){};
Options.prototype = {
getMode: function(){
return chrome.storage.sync.get("value", function(e){
console.log(e); // it prints 'Object {value: "test"}'.
return e;
});
},
setMode: function(){
chrome.storage.sync.set({"value": "test"}, function(e) {
})
}
}
var options = new Options();
options.setMode();
console.log(options.getMode()); // it prints 'undefined'.
I expected it to print
Object {value: "set up"}
when I call options.getMode(), but it prints undefined.
Does anyone know how to fix this problem?
The chrome.storage API is asynchronous - it doesn't return it directly, rather passing it as an argument to the callback function. The function call itself always returns undefined.
This is often used to allow other methods to run without having to wait until something responds or completes - an example of this is setTimeout (only difference is that it returns a timer value, not undefined).
For example, take this:
setTimeout(function () { alert(1); }, 10000);
alert(0);
Because setTimeout is asynchronous, it will not stop all code until the entire function completes, rather returning initially, only calling a function when it is completed later on - this is why 0 comes up before 1.
For this reason, you cannot simply do something like:
// "foo" will always be undefined
var foo = asyncBar(function (e) { return e; });
Generally, you should put what you want to do in your callback (the function that is called when the asynchronous function is completed). This is a fairly common way of writing asynchronous code:
function getValue(callback) {
chrome.storage.sync.get("value", callback);
}
You could place an entire portion of your code inside the callback - there's nothing stopping you from doing so. So instead of doing the following:
console.log(getValue()); // typical synchronous method of doing something
This would probably be a better idea:
// how it would be done in asynchronous code
getValue(function (value) {
console.log(value);
});
Chrome storage API is asynchronous and it uses callback, that's why you're getting this behavior.
You can use Promise API to overcome this asynchronous issue, which is simpler and cleaner. Here is an example:
async function getLocalStorageValue(key) {
return new Promise((resolve, reject) => {
try {
chrome.storage.sync.get(key, function (value) {
resolve(value);
})
}
catch (ex) {
reject(ex);
}
});
}
const result = await getLocalStorageValue("my-key");
The chrome.storage.sync.get is called asynchronously, that's why you have to pass it a callback, so that it is executed in the future.
When you try to print the returned value of getModeyou are printing the return value of whatever chrome.storage.sync.get returns after queuing the asynchronous call to be executed.
This is a common mistake people do in javascript, while they are learning to use asynch calls.

Categories