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;
});
};
Related
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I have a chrome extension. Its code has a method getSelectionFromPage() which catches the text selected on the webpage and always returns true like below:
function getSelectionFromPage() {
window.selected = true;
chrome.tabs.executeScript({
code: "window.getSelection().toString();"
}, function(selection) {
if (selection[0] != '') {
window.selected = true;
}else{
window.selected = false;
}
});
return true
}
On the same window context, I ran the following commands on the console.
The result can be seen as follows:
I am writing the same commands here also:
getSelectionFromPage() //-> true
window.selected //-> false
(getSelectionFromPage() && window.selected) //-> true
The (getSelectionFromPage() && window.selected) should be false. I have tried checking typeof(window.selected) and typeof(getSelectionFromPage()) and both are returning boolean. I don't understand why it is happening.
The function which is setting to false is a callback. This will not execute until after the current execution context is complete. Therefore, it will not be set to false until after && window.selection completes execution.
executeScript docs: https://developer.chrome.com/extensions/tabs#method-executeScript
The order of things is:
(function () {
window.selected = true; // Runs
chrome.tabs.executeScript({code: "window.getSelection().toString();"}, function(){
window.selected = false;
}); // Calls browser API and set's callback (the anonymous function there) to call later)
// NOTE: the callback function which was set here was NOT executed yet it was only defined.
return true;
})() // true
&& window.selected // this is currently true
// Later, now callback executes
If you would like to wait, you could use a Promise instead.
function getSelectionFromPage() {
return new Promise(function (resolve) {
chrome.tabs.executeScript(
{code: "window.getSelection().toString();"},
// or just put resolve here instead of defining a function to get value directly
function(v){
resolve(!!v);
}
);
});
}
getSelectionFromPage().then(haveSelection => console.log(haveSelection);
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.
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
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I was trying to return a value after an ajax call in a function and it kept returning undefined.
I looked it up and learned about callbacks.
I am starting to understand the concept, but little confused over handling it the way I want to
The function:
function count_posts(post_type, callback) {
var s_data = {
count_posts: 1,
post_type: post_type
}
$.post("actions.php", s_data, function(data) {
var r = JSON.parse(data);
callback(r);
});
} // EO count_posts
calling it:
count_posts('all', function(count) { console.log(count); }); // 20 ( working )
handling it differently:
console.log(count_posts('all', function(count) { return count; })); // undefined
Goal:
$('#show_count').html(count_posts('all', function(count) { return count; }))
How do I handle a callback in the way that I want to handle it.
The function doesnt return a value.
The callback is called async
try calling it like this:
count_posts('all', function(count) {
$('#show_count').html(count);
});
The point with such callbacks is, that they are somewhat "called from nowhere".. so you will not return it a value to your code. Instead reverse the call order, in your example:
count_posts('all', function(count) { $('#show_count').html(count); });
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);
});