i need to used instant variable inside the object define function like that .
i need to use Result variable outside the function
function Request(params,type,url){
var loginReq = Titanium.Network.createHTTPClient();
loginReq.open(type,url);
loginReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
loginReq.setRequestHeader("enctype", "multipart/form-data");
loginReq.setRequestHeader("Content-Type", "image/png;charset=utf-8");
loginReq.send(params);
loginReq.onload = function()
{
var json = this.responseText;
var Result = JSON.parse(json);
};
return Result;
};
exports.Request = Request;
i need to return Result Or use it outside the scope.
You need to use either a callback, or a promise library
Using a callback
function Request(params,type,url,callback){
//...
loginReq.onload = function() {
var json = this.responseText;
var Result = JSON.parse(json);
callback(Result);
};
};
//Somewhere else
Request(/**/,/**/,/**/,function(result){
//use result
});
Using a promise library like Q
var Q = require("q");
function Request(params,type,url,callback){
var deferred = Q.defer();
//...
loginReq.onload = function() {
var json = this.responseText;
var Result = JSON.parse(json);
deferred.resolve(Result);
};
return deferred.promise;
};
//Somewhere else
Request(/**/,/**/,/**/).then(function(result){
//use result
});
Related
I have the following script on http://foobar.com/api?callback=mycallback:
var something = 'aaa';
var callback = mycallback;
(function() {
var output = eval(something);
callback(output);
});
And I want to access this script from my own script, and fetch the output. So I am doing the following:
var module1 = (function() {
var getFromApi = function(output) {
return (function(output) {
var script = document.createElement('script');
script.setAttribute('src', 'http://foobar.com/api?callback=mycallback');
document.getElementsByTagName('head')[0].appendChild(script);
});
};
var fetch = function() {
getFromApi(function(output) {
console.log(output);
});
};
return {
fetch: fetch
};
})();
module1.fetch();
The result should be the output from this script, but it is not, it doesn't even enters the callback. How can I do this properly?
There are some problems in module1:
getFromApi returns a function (let's call it fn)
fn has a parameter named output that shadows the argument of the outer function making the argument passed to getFromApi useless
fetch calls getFromApi and it does nothing else
the callback function must be globally accessible
A possible solution could be:
var module1 = (function() {
var getFromApi = function(output) {
var script = document.createElement('script');
script.setAttribute('src', 'http://foobar.com/api?callback='+output);
document.getElementsByTagName('head')[0].appendChild(script);
};
var fetch = function() {
getFromApi('myfunction');
};
return {
fetch: fetch
};
})();
function myfunction(output) {
console.log(output);
}
module1.fetch();
Possible nasty solution for function as callback (It will not work in IE but can be adapted)
var module1 = (function() {
var getFromApi = function(output) {
var script = document.createElement('script');
script.setAttribute('src', 'http://foobar.com/api?callback=eval(document.currentScript.dataset.fn)');
script.setAttribute('data-fn', '(function(){ return ' + output +'})()');
document.getElementsByTagName('head')[0].appendChild(script);
};
var fetch = function() {
return getFromApi(function(output){
console.log(output);
/*remember to remove script tag*/
document.currentScript.remove();
});
};
return {
fetch: fetch
};
})();
module1.fetch();
I am developing a NodeJS application and encountered following problem:
I am using node module node-rest-client to issue REST requests using an API. I use post method provided by the module for my purpose. I need to fetch the json response and write it to seperate variables and return them.
I have defined returnData variable outside the client.post method. I need to update this returnData variable inside the function which is passed as a parameter to the client.post method.
But I have a scope issue here. Although I try to update the returnData variable inside that function, when execution returns from client.post function, I see that the same values I have set (in this case null, but may be any value) before calling client.post function still persists in the variable.
How can I define scope well so that I can update an outside variable inside the function which I pass as a parameter to another function? Any help would be greatly appreciated.
Following is my Code:
module.exports = function(){
require("../config");
var restClient = require('node-rest-client').Client;
var client = new restClient();
var sessionID = null,
reqID = 1;
var login = function(username, password){
var requestParams = {};
var apiParams = {};
requestParams.jsonrpc = "2.0";
requestParams.method = ZABBIX_API_METHODS.login;
apiParams.user = username;
apiParams.password = password;
requestParams.params = apiParams;
requestParams.id = reqID;
requestParams.auth = null;
var args = {
data: requestParams,
headers:{"Content-Type": "application/json-rpc"} // ask response type to be application/json-rpc
};
var returnData = {};
returnData.status = null;
returnData.data = null
client.post(ZABBIX_API, args, function(resData,rawRes){
if(rawRes.statusCode == 200){
returnData.status = rawRes.statusCode;
returnData.data = resData;
}
else{
returnData.status = rawRes.statusCode;
returnData.data = "Request Failed!";
}
reqID = reqID + 1;
console.log(returnData.data);
});
console.log("SessionID:"+getSessionID());
return returnData;
}
var functions = {
login: login
}
return functions;
}
Thank you.
.post is Async, you should do it like this,
var login = function(username, password, callback){
..................
client.post(ZABBIX_API, args, function(resData,rawRes){
if(rawRes.statusCode == 200){
returnData.status = rawRes.statusCode;
returnData.data = resData;
}
else{
returnData.status = rawRes.statusCode;
returnData.data = "Request Failed!";
}
reqID = reqID + 1;
return {login: returnData};
});
//remove all below return statements
I have some data in a IndexedDB table that quite simply contains this data:
var Customers = [
{ ssn: "123-45-6666", name: "Andrew", age: 22, email: "andrew#hotmail.com" },
{ ssn: "555-66-7777", name: "Gail", age: 25, email: "gail#email.me" }
];
I then have this function to get data back from the IndexedDB:
function RetrieveTableRows(Table) {
var returnData = [];
var db = window.indexedDB.db;
var trans = db.transaction([Table], "readwrite");
var store = trans.objectStore(Table);
var keyRange = IDBKeyRange.lowerBound(0);
var cursorRequest = store.openCursor(keyRange);
cursorRequest.onerror = window.indexedDB.onerror;
cursorRequest.onsuccess = function(e) {
var result = e.target.result;
if(!!result == false) {
return;
}
returnData.push(result.value);
result.continue();
};
return returnData;
}
I realise that it does not work because the onsuccess function is asynchronous, however I can't my head around a solution.
Simply, I want to be able to write:
var myCustomers = RetrieveTableRows('customers');
and be able to then use the variable myCustomers - is this possible?
I have tried using JQuery.deferred(); method but that didn't seem to work, and I know that I could possibly do something like this:
transaction.oncomplete = function() {
ReturnTableRows(returnData);
};
}
function ReturnTableRows(data) {
//do something with the array of data
}
but I can't work out how to pass this back to the myCustomers variable.
Using the deferred object you should be able to do something like this
function RetrieveTableRows(Table) {
var returnData = [];
//setup deferred object
var defer = $.Deferred();
var db = window.indexedDB.db;
var trans = db.transaction([Table], "readwrite");
var store = trans.objectStore(Table);
var keyRange = IDBKeyRange.lowerBound(0);
var cursorRequest = store.openCursor(keyRange);
cursorRequest.onerror = window.indexedDB.onerror;
cursorRequest.onsuccess = function(e) {
var result = e.target.result;
if(!!result == false) {
//when done resolve the promise, you could also do more
//checking and reject the data so you can handle
//errors
defer.resolve(returnData);
//Make sure we exit the function once we run out of data!
return
}
returnData.push(result.value);
result.continue();
};
//return the promise
return defer.promise();
}
//########### then to use this ###########
//this is now a promise
var myCustomersPromise = RetrieveTableRows('customers');
var myCustomers;
//action todo when promise is resolved/rejected
$.when(myCustomersPromise ).done(function(data){
//do something with the data/assign it to you var here
myCustomers= data;
}).fail(function(data){
});
although i have not actually used indexedDB before so maybe misunderstanding how the query knows it is finished ( I am asssuming result.continue() called the onSuccess again and the result is false when it has gone through all the data) but this is the setup I use when doing anything asynchronously in my apps
An alternate method I've found that uses less code, is a lot simpler and doesn't require JQuery.
Setup:
// Create the function(s) to grab and store the data
var myCustomers;
var getData = {
customers: function(data) {
myCustomers = data
}
}
Call:
//Send the callback function we want into the retrieve function
trans.oncomplete = function (e) {
RetrieveTableRows('Customers', getData.customers)
};
Function:
function RetrieveTableRows(Table, Callback) {
var returnData = [];
var db = window.indexedDB.db;
var trans = db.transaction([Table], "readwrite");
var store = trans.objectStore(Table);
var keyRange = IDBKeyRange.lowerBound(0);
var cursorRequest = store.openCursor(keyRange);
cursorRequest.onerror = window.indexedDB.onerror;
cursorRequest.onsuccess = function(e) {
var result = e.target.result;
if(!!result == false) {
// Send the information back to our specified function
Callback(returnData);
return
}
returnData.push(result.value);
result.continue();
};
}
I'm developing a Javascript libraray which I want to use as follows.
var obj = new Lib().actionOne();
This call should populate "transcript" and "session" member variables in obj.
Then I want to call:
obj.actionTwo();
which will use populated "transcript" and "session" objects in the previous call.
Find below my library.
var xmlhttp = null;
function Lib() {
this.transcript = null;
this.session = null;
return this;
}
Lib.prototype = {
_initRequest : function() {
// create xmlhttp request here
},
_consumeService : function(callback) {
this._initRequest();
xmlhttp.open("GET", "THE URL", true);
var self = this;
xmlhttp.onreadystatechange = function(self) {
if(xmlhttp.readyState==4 && xmlhttp.status==200 ){
callback.call(self);
}
};
xmlhttp.send();
},
actionOne: function() {
var connUrl = "SOME URL";
this._consumeService(this._actionOneCallback);
return this;
},
_actionOneCallback : function() {
var jsonObj = JSON.parse(xmlhttp.responseText);
this.session = jsonObj.session
this.transcript = jsonObj.transcript;
this.isActionOneDone = true;
xmlhttp = null;
},
actionTwo : function() {
// use this.session and this.transcript
}
};
The issue is that actionOneCallback() function doest not populate 'obj' members though I pass 'self' reference to it. Therefore when I call 'obj.actionTwo();', obj's member variables are undefined. What is the workaround for this?
I don't understand why this code doesn't work for me
var rest = require('restler');
var getResp = function(url){
var resp ="";
rest.get(url).on('complete',function(response){
resp = response.toString();
});
return resp;
};
I am not getting the response for getResp('google.com')
Am I missing something with restler?
Being that you're returning resp it looks like you've forgotten that the request is asynchronous. Instead try out this:
var rest = require('restler');
var getResp = function(url){
rest.get(url).on('complete', function(response){
console.log(response);
});
};
getResp('http://google.com/');
// output:
// <!doctype html><html itemscope="itemscope" ....
Because of its asynchronous nature it's preferred that you pass the value to a receiving callback. Take this small example:
var rest = require('restler');
// process an array of URLs
['http://google.com/',
'http://facebook.com/'].forEach(function(item) {
getResp(item);
});
function getResp(url){
rest.get(url).on('complete', function(response){
processResponse(response);
});
};
// data will be a Buffer
function processResponse(data) {
// converting Buffers to strings is expensive, so I prefer
// to do it explicitely when required
var str = data.toString();
}
Once the data comes in you'll be able to pass it around like any other variable.
return resp; is running before the on('complete' callback gets called because it is asynchronous. This is resulting is the resp variable never getting assigned a value.
Try this:
var rest = require('restler');
var getResp = function(url){
var result = rest.get(url).on('complete', function(response){
response;
});
return result;
};
getResp('http://google.com/');
You could also use a callback like in this SO answer.