How to extend the scope of a function variable in javascript? [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
How to return value from an asynchronous callback function? [duplicate]
(3 answers)
Closed 6 years ago.
I have a basic function in protractor written as :
this.getCurrentUrl = function () {
browser.getCurrentUrl().then(function(url){
console.log('url : '+url);
});
};
Now is there a way I can access the 'url' outside of the inner function scope, because I need to return this value to some other function calling this one. I need to get the value and return it from outside of then(function(url){...}

the url will be acquired async, so you can't just assign it. You probably want to hand it a callback.
function handleUrl(url) {
// here is where you do something with the url
}
// let your callback be called
this.getCurrentUrl = function(fn) {
browser.getCurrentUrl().then( function (url) {
fn(url);
})
}
// make the call with your handler
this.getCurrentUrl(handleUrl);
Another approach is to have your function return a "container" and that gets inflated later. Then later you can check your container. Since the behavior is async, you won't know when it will be ready, so you can check for it on an interval or something...
// return a container object
this.getCurrentUrl = function() {
var urlContainer = {};
browser.getCurrentUrl().then( function (url) {
urlContainer.url = url;
});
return urlContainer;
}
var urlContainer = this.getCurrentUrl(); // starts off as an empty object
urlContainer.url // undefined
// then shortly in the future
urlContainer.url // has some url
Yet a third way is to return a closure
this.getCurrentUrl = function() {
var urlValue;
browser.getCurrentUrl().then(function(url) {
urlValue = url;
});
return function() {
return urlValue;
}
}
var getUrl = this.getCurrentUrl();
getUrl(); // initially, returns undefined;
// keep trying. then shortly in the future...
getUrl(); // now has the url

Related

How I can return a string from a javascript callback [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
How I can return a string from a javascript callback
I have two functions, main function is working on loaded.
and another function is used to calling web service.
I would like to know how can JS return the string value to main function.
thanks
function thisCallJSON(webServiceURL) {
var params = {};
params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.GET;
gadgets.io.makeRequest(webServiceURL, function(response)
{
if(response.data && response.text)
{
var jsondata = response.data;
for (var key in jsondata)
{
var value = jsondata[key];
//alert("Member Name : "+value["memNm"]);
}
}
else
{
//alert("Member Name : Not Found !");
}
}, params);
}; function main(){
var txt_string = "";
txt_string = thisCallJSON("http://192.100.1.59");
}
You can assign the value to the variable in the scope of the main function, but it won't happen before the main function is finished executing because of the event loop. Instead, you should put your code inside the callback, or better yet, look at how you would use javascript promises to accomplish this.

Protractor resolve promise within function [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
There are two elements on the GUI, depending on the context only a single is visible.
Therefore, i like to use a helper function that gives the the Protractor element of the currently visible element.
However, i have to wait until the promise is resolved since everything is asynchronous.
function () {
var result;
var controlA = $('controlA');
var controlB = $('controlB');
listControl.isDisplayed().then(function (isVisible) {
result = isVisible;
// STEP X
});
// WAIT HERE UNTIL STEP X is done
return result ? controlA : controlB;
};
Clarification: I do NOT want to wait until the control is getting visible.
You can directly return the control inside the isDisplayed() promise itself.Look at below example code.
function () {
var result;
var controlA = $('controlA');
var controlB = $('controlB');
return listControl.isDisplayed().then(function (isVisible) {
return isVisible ? controlA : controlB;
});
};

Why is my function not returning the array? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
This is my code:
document.getElementById('revealUser').onclick = displayDaUsers
function displayDaUsers(){
pullAllUsersFromDB();
debugger;
}
function pullAllUsersFromDB(){
rootRef.child('users').on('value', function(snapshot) {
var users_array = [];
var users_object = snapshot.val();
Object.keys(users_object).map(function(key) {
users_array.push(users_object[key]);
});
// window.dateApp.allUsers = users_array;
return users_array
});
}
html:
<input type="submit" id="revealUser" value="reveal user">
I put a debugger in to see the problem but it does not help. When I go into the console and type in users_array
I get Uncaught ReferenceError: users_array is not defined(…)
NEW CODE (EDIT):
according to another stackoverflow answers this should work..
function displayDaUsers(){
var test = pullAllUsersFromDB();
console.log(test);
//pullAllUsersFromDB();
//debugger;
//setUpFirstUser()
}
function pullAllUsersFromDB(){
rootRef.child('users').on('value', function(snapshot) {
var users_array = [];
var users_object = snapshot.val();
Object.keys(users_object).map(function(key) {
users_array.push(users_object[key]);
});
//window.dateApp.allUsers = users_array;
return users_array
});
}
The return value users_array is local to the scope of the anonymous callback function function(snapshot) {.... In other words, its value is lost outside of that scope.
At what point in your logic do you need access to user_array? If you need access to it outside of the context of your functions, maybe it makes sense to define a variable with greater scope, and then setting its value in your anonymous function. E.g.
document.getElementById...
var arr;
...
function pullAllUsersFromDB() {
...
...function(snapshot) {
arr = users_array;
});
}
// pullAllUsersFromDB() (and its callback) must be called for arr to be defined at this point in execution

Run function only once - functional programming JavaScript [duplicate]

This question already has answers here:
Implementing a 'once' function in JavaScript
(3 answers)
Closed 8 years ago.
I have a code below,
var a = 0;
var addByOne = doOnce(function() { a += 1; });
// I need to define a doOnce function here
// Run addByOne two times
addByOne();
addByOne();
This will result the variable a holds 2 as its value. My question is, how do I make the doOnce function so that it will result in running the function inside doOnce (in the case above, function () { a += 1; } ) just one time. So no matter how many times addByOne is called, variable a will be incremented just once.
Thanks
This can be achieved by creating a doOnce function which returns a wrapper for calling the passed function if it has not already been run. This may look something like this;
doOnce = function(fn) {
var hasRun = false,
result;
return function() {
if (hasRun === false) {
result = fn.apply(this, arguments);
hasRun = true;
}
return result;
}
}
Try this:
function doOnce(fn) {
// Keep track of whether the function has already been called
var hasBeenCalled = false;
// Returns a new function
return function() {
// If it has already been called, no need to call it again
// Return (undefined)
if (hasBeenCalled) return;
// Set hasBeenCalled to true
hasBeenCalled = true;
return fn.apply(this, arguments);
}
}
If you want, you can keep track of the return value and return that instead of undefined.

js function inside function and wait for return value [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
How to return AJAX response Text? [duplicate]
(2 answers)
Closed 9 years ago.
$(document).ready(function(){
// Global function (will be include in any HTML file)
function m3_result(size_1, size_2, size_3){
$.get('http://www.google.com', function(data){
return data;
});
}
// Another function
function calculate(){
var size_1 = parseFloat($('#add_document_form #size_1').val());
var size_2 = parseFloat($('#add_document_form #size_2').val());
var size_3 = parseFloat($('#add_document_form #size_3').val());
var ax = m3_result(size_1, size_2, size_3);
alert(ax); // Here ax return: UNDEFINED
}
// Run
calculate();
});
Results are "undefined", but I would like that calculate() will wait for m3_result() to execute. I see that here problem is coming when I added $.get(), but its needed...
I have searching for callback() like functions, but none fit to my needs, or I just didnt put that right.
Any help will be highly appreciated, thanks.
GET url will be localy and element IDs are also ok.
You can't return a result from an asynchronous function, instead you can return a promise to supply that value later, which as it happens is the jqXHR object returned by $.get:
function m3_result() {
return $.get(...)
}
and do the same in calculate:
function calculate() {
...
return m3_result(...);
}
and then wait for the result, which will be passed as a parameter to the callback registered with the .done function:
calculate().done(function(result) {
alert(result);
});

Categories