Retrieve object from asyncronous function in bpmn moodle - javascript

I have function where I am using bpmn moddle to create bpmn xml.
Below is my function createFileData
import BpmnModdle from 'bpmn-moddle'
function createFileData(){
var moddle = new BpmnModdle()
var xmlStr =
'<?xml version="1.0" encoding="UTF-8"?>' +
'<bpmn2:definitions xmlns:bpmn2="http://www.omg.org/spec/BPMN/20100524/MODEL" ' +
'id="empty-definitions" ' +
'targetNamespace="http://bpmn.io/schema/bpmn">' +
'</bpmn2:definitions>';
moddle.fromXML(xmlStr, function(err, definitions) {
// update id attribute
definitions.set('id', 'NEW ID');
moddle.toXML(definitions, function(err, xmlStrUpdated){
console.log(xmlStrUpdated)
})
})
return xmlStrUpdated
}
I am getting the output in the console.
I want the xml created to be returned, when ever the function is called.
But I am getting the value as undefined and unable to return data to below function.
import createFileData from './fileData.js'
function viewxml(){
var data = createFileData()
console.log(data)
}
Can anyone help me in understanding, how to return the xml created from moddle?

Related

How can I obtain API response data from within a function? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
Javascript noob here. Apologies if there are a ton of duplicate questions out there because it seems like this must be a fundamental js function thing, but I honestly can't find an answer to this. I'm trying to wrap an API GET call in a function, and I'm running into behavior that I don't understand. The code in question:
I'm using the node-rest-client package to call the mapquest geocoding API. I'm interested in the lat/long data only.
var Client = require('node-rest-client').Client;
If I make the GET call like this, I can access parsed as an object, which is what I want.
var address = 'New York'
var client = new Client();
var parsed;
client.get("http://www.mapquestapi.com/geocoding/v1/address?" +
'key=' + mapquestKeys.consumer_key +
'&location=' + address,
function(data, response) {
parsed = data.results[0].locations[0].latLng
}
);
// parsed == {lat, long}
But if I wrap this in a function:
function geocode(address){
var client = new Client();
var parsed;
client.get("http://www.mapquestapi.com/geocoding/v1/address?" +
'key=' + mapquestKeys.consumer_key +
'&location=' + address,
function(data, response) {
parsed = data.results[0].locations[0].latLng
}
);
return parsed
}
var address = 'New York'
parsed = geocode(address);
// parsed === undefined
parsed doesn't seem to be affected by the inner function; it's undefined. How can I return parsed as an object containing the data I want as in the first example? What the heck is going on here?
In:
function geocode(address){
var client = new Client();
var parsed;
client.get("http://www.mapquestapi.com/geocoding/v1/address?" +
'key=' + mapquestKeys.consumer_key +
'&location=' + address,
function(data, response) {
parsed = data.results[0].locations[0].latLng
}
);
return parsed
}
var address = 'New York'
parsed = geocode(address);
// parsed === undefined
You never defined parsed outside of the scope of your function. Also you're returning parsed inside of the function before it's had a chance to retrieve from the GET request. If you wanted to do it this way, you'd need to put return(prased) inside the callback function of client.get. A better way to do it is to wrap it inside a Promise like so:
function geocode(address){
return new Promise((resolve, reject) => {
var client = new Client();
client.get("http://www.mapquestapi.com/geocoding/v1/address?" +
'key=' + mapquestKeys.consumer_key +
'&location=' + address,
function(data, response) {
if(data){
resolve(data.results[0].locations[0].latLng)
}
else{
reject(response)
}
});
})
};
var address = 'New York';
var parsed;
geocode(address).then(function(latlong){
parsed = latlong
}).catch(err => {
console.log(err)});
Here, parsed will only evaluate to latlong once the Promise has been resolved (the GET request has returned successful). It will also reject the Promise if data of the GET request is NULL and return an error.
If you wanted to then do something with parsed you could include that in the .then() statement.
Learning how to code in Javascript means learning how to write code asynchronously. Promises help you treat things which are by default asynchronous as synchronous.
You never defined parsed in scope (externally to the function):
function geocode(address){
var client = new Client();
var parsed;
client.get("http://www.mapquestapi.com/geocoding/v1/address?" +
'key=' + mapquestKeys.consumer_key +
'&location=' + address,
function(data, response) {
parsed = data.results[0].locations[0].latLng
}
);
return parsed
}
var address = 'New York'
var parsed = geocode(address);
Notice the var parsed = geocode(address);
you need to wrap this into a promise, or return the result with callback. Callback would be like this:
function call(arg, callback) {
client.get("http:////" + arg, function (data, response) {
callback(data.results[0].locations[0].latLng)
});
}
call("yolo", function (parsed) { console.log(parsed) })
promise is well described here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

AQL Query returns a Promise

I have been trying to get a query result from Arangodb in to my front end service(Angular 4) using soap message. I am able to get a result of the query but printed out in console.log. But how can I get it under this function(myService).
In other words, How can I feed my query result into a function rather than printing out the result in console. So that I can use this function to get the output of the query?
I have used .then() as well in order to get the promise.What am I still missing in it ?
server.js
var myService = db.query(aqlQuery`
LET startVertex = (FOR doc IN spec
FILTER doc.serial_no == '"123456abcde"'
LIMIT 2
RETURN doc
)[0]
FOR v IN 1 ANY startVertex belongs_to
RETURN v.ip`,
{
bindVar1: 'value',
bindVar2: 'value',
})..then(function(res) {
console.log("documents:" + res._result);
})
I would like to feed the function into soap msg and receive it Angular 4,
soap msg
var soap_msg = '<soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:examples:CheckUserNameService">' +
'<soapenv:Header/>' +
'<soapenv:Body>' +
'<urn:CheckUserNameResponse soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">' +
'<status xsi:type="xsd:string">' + (myService) + '</status>' +
'</urn:CheckUserNameResponse>' +
'</soapenv:Body>' +
'</soapenv:Envelope>';
var server = http.createServer(function(request,response) {
response.end(soap_msg);
});
var port = 8000;
server.listen(port);
var soapServer = soap.listen(server, '/test', myService, xml);
But the output is either empty braces If I am using JSON.stringify or else it is [object Promise]. What am I doing wrong here ?
output

How do I display JSON data to an HTML DOM Element after JSON.parse()?

I have two functions I am using to pull JSON from my server side to then display it to HTML.
The first function that pulls the data from the route handler is successfully pulling the data and parsing it successfully with JSON.parse() and displaying the needed information to the console without issue. I am not having and ajax or route handling issue...
Here is how I am dealing with the JSON first in my function called "projectInfo()":
projInfo = JSON.stringify(data);
console.log("DEBUG DONE WITH CAPTURING project_info DATA: " );
// This console.log() prints the JSON string
// successfully pulled from route handler
// var projInfo is a local string var declared in the scope of
// this first function
console.log("var projInfo: " + projInfo);
// parse JSON data in projInfo and store in string var p
// string var p is a local var declared inside of the scope
// of this function
p = JSON.parse(projInfo);
console.log("Parsed Project JSON: " + p.Project);
// update "Global" pInfo with the value of the JSON data for
// "Project" as needed
pInfo = p;
console.log("What is inside of pInfo???: " + pInfo);
// This last console.log prints [object Object] to console
// How do I pul the value out of this Object?
The second function calls the first function in order to update a global variable with the parsed JSON data that I need to then display the global variable's data to the DOM element that I am trying to display.
Here is how I am trying to update my global var with a JSON Object in my function called "loginFun()":
// Call projectInfo() in order to update Global pInfo
// with the needed project info
projectInfo();
// This console.log() prints nothing...?
console.log("projectInfo var data should be aa2: " + pInfo);
document.getElementById("userBar").style.display = "";
// This is where I try to Display pInfo in the DOM but I only get Undefined...?
document.getElementById("signedinas").innerHTML = "<font face=\"verdana\" size =\"4\" color=\"white\">Logged in as: " + username + " Project: " + pInfo + " </font>";
When I JSON.parse() the data in the first function I run a console.log() statement and I get the needed data to print from a variable local to the function I am getting my JSON with using ajax and I verify that the function is in fact doing what I need so that part is good up until I get the [object Object] output.
I am having issues when I call this function from my second function to then try to use the global variable which should have the data stored.
when I try to use the global variable with the needed data I get an 'undefined'...
I have also tried returning the data that has been parsed in the first function to then storehttps://codepen.io/lopezdp/pen/owKGdJ the value returned into a local variable in the second function but I still get 'undefined'.
If you would like to see the complete code for both functions I have put them on a CodePen to make it easier at:
https://codepen.io/lopezdp/pen/owKGdJ
How can I get my Project Data to display in my DOM element?
EDIT: The JSON Data that I am using looks like this:
{"User":"aa2","Owner":"aa2_role","Status":"locked","Port":"5432","Description":"Transferred from CFS01 on Jun29","Project":"aa2","Server":"localhost"}
I rewrote your login function like this and it worked for me. I also eliminated the projectInfo() function!
var allMn = [];
var tags = [];
var pInfo = '';
function loginFun() {
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;
if (username == "" || password == "") {
alert("Required fields cannot be left blank.");
} else {
$.ajaxSetup({
cache: false
});
$.ajax({
type: 'GET',
url: 'http://139.169.63.170:' + port + '/login/' + username + "zlz" + password,
cache: false,
success: function (data) {
// NEED SUB ROUTINE HERE FOR AJAX CALL DPL
// Make async call to ccdd tool database to get new data
// This collects allMn[] data!!!
getMnJson();
// END SUB ROUTINE HERE
// Checks to make sure user is logged in if not
// the condition redirects user to loginFun()
if (data.search("HTTP ERROR: ") != -1) {
alert("Login Failed.");
document.getElementById('username').value = "";
document.getElementById('password').value = "";
document.getElementById('searchResults').innerHTML = "Login Failed";
document.getElementById('searchRBar').style.display = "";
loginFun();
} else {
login = 1;
// Call projectInfo() in order to update pInfo with the needed project info
//projectInfo();
var projInfo = '';
var p = '';
// Get all Mn Data on startup tp display in DOM -DPL
$.ajax({
type: 'GET',
url: 'http://139.169.63.170:' + port + '/role',
dataType: 'json',
cache: true,
success: function (data) {
// projInfo = JSON.stringify(data);
console.log("DEBUG DONE WITH CAPTURING project_info DATA: " );
// console.log("var projInfo: " + projInfo);
// parse JSON data in projInfo
p = data['Project']; //JSON.parse(projInfo);
console.log("Parsed Project JSON: " + p);
// update "Global" pInfo with the value of the JSON data for "Project" as needed
pInfo = p;
console.log("What is inside of pInfo???: " + pInfo);
document.getElementById("signedinas").innerHTML = "<font face=\"verdana\" size =\"4\" color=\"white\">Logged in as: " + username + " Project: " + pInfo + " </font>";
}
}).fail(function () {
alert("Login Failed.");
document.getElementById('username').value = "";
document.getElementById('password').value = "";
console.log("Error. /role data access Error.");
});
console.log("projectInfo var data should be aa2: " + pInfo);
document.getElementById("userBar").style.display = "";
// Display pInfo in the DOM
// document.getElementById("signedinas").innerHTML = "<font face=\"verdana\" size =\"4\" color=\"white\">Logged in as: " + username + " Project: " + pInfo + " </font>";
$("div.create").children().remove();
//-------------------------------------------------------------------END OF GLOBAL VARIABLES
$.ajaxSetup({
cache: false
});
// get table data from proxy server on port 7071 DPL
// NEED SUB ROUTINE HERE FOR AJAX CALL
// Make call to server-side code to reload JSON data into table from port 7071
pushJsonData();
// END SUB ROUTINE HERE!!!
// getTblJson();
}
}
}).fail(function () {
alert("Login Failed.");
document.getElementById('username').value = "";
document.getElementById('password').value = "";
console.log("Error. Need user Credentials");
});
}
}

PhoneGap Barcode Scanner results not being passed to variable

I have a JavaScript function in a PhoneGap app that makes a successful call to the barcode scanner (using the Cordova plugin). I then form a JSON string and make a 'return' call in an attempt to pass the string back to the function call assignment. I successfully alert the JSON string in the scanning function but then get an undefined value for the variable that's been assigned the function result. I'm thinking that this might have to do with scope but declaring the variable outside of the function didn't make any difference.
var myscan = null;
var myclueJSON = null;
var myscan = getScan(); //call scanning function and assign result JSON to myscan variable
alert(myscan); //returns undefined
//call PhoneGap barcode scanner function
//and form JSON to return
function getScan()
{
var scanner = cordova.require("cordova/plugin/BarcodeScanner");
scanner.scan( function (result)
{
var myresult = result.text;
var obj= JSON.parse(myresult);
//fetch event id from barcode
var myeventid = obj.eventid;
//fetch clue sequence from barcode
var mycluesequence = obj.cluesequence;
//form JSON string
var myscanJSON = '{"eventid":"' + myeventid + '","cluesequence":"' + mycluesequence + '"}';
//return JSON string
return myscanJSON;
}, function (error)
{
console.log("Scanning failed: ", error);
});
It may be due to the fact you're trying to return myscanJSON within the callback function. You could try declaring an empty string outside the callback then append to it like so:
var myscan = null;
var myclueJSON = null;
var myscan = getScan(); //call scanning function and assign result JSON to myscan variable
alert(myscan); //returns undefined
//call PhoneGap barcode scanner function
//and form JSON to return
function getScan()
{
var scanner = cordova.require("cordova/plugin/BarcodeScanner"),
myscanJSON = '';
scanner.scan( function (result)
{
var myresult = result.text;
var obj= JSON.parse(myresult);
//fetch event id from barcode
var myeventid = obj.eventid;
//fetch clue sequence from barcode
var mycluesequence = obj.cluesequence;
//form JSON string
myscanJSON += '{"eventid":"' + myeventid + '","cluesequence":"' + mycluesequence + '"}';
}, function (error)
{
console.log("Scanning failed: ", error);
});
//return JSON string
return myscanJSON;
}
Or you could refactor your callback function:
var myscan = null;
var myclueJSON = null;
var myscan = scanner.scan(getScan(result), handleError(error)); //call scanning function and assign result JSON to myscan variable
alert(myscan); //returns undefined
//call PhoneGap barcode scanner function
//and form JSON to return
function getScan(result)
{
var myresult = result.text;
var obj= JSON.parse(myresult);
//fetch event id from barcode
var myeventid = obj.eventid;
//fetch clue sequence from barcode
var mycluesequence = obj.cluesequence;
//form JSON string
var myscanJSON = '{"eventid":"' + myeventid + '","cluesequence":"' + mycluesequence + '"}';
//return JSON string
return myscanJSON;
}
function handleError(error){
return error;
}
I refactored the code. It did have a bit of a challenge that I didn't mention. The barcode scanner call needed to be initiated after a successful geolocation call. Since these want to complete asynchronously, I had to nest the getScan function inside the geolocation success function, passing in a simple lat/lng JSON object to the scan function which eventually forms a longer JSON string and makes a jQuery AJAX call to write to a database.
//get current position function
function fetchGeolocation()
{
navigator.geolocation.getCurrentPosition(fetchCoords, handle_error);
}
//extract current coords
function fetchCoords(p)
{
mylocjson = '{"lat":"' + p.coords.latitude + '","lng":"' + p.coords.longitude + '"}';
//fire up scanner, passing in lat/lng JSON string
getScan(mylocjson);
}
//fire up PG scanner and form JSON result object
function getScan(incominglocjson)
{
//parse lat/lng
var clueobj = JSON.parse(incominglocjson);
var scanner = cordova.require("cordova/plugin/BarcodeScanner");
scanner.scan(function (result)
{
var myresult = result.text;
var obj= JSON.parse(myresult);
//fetch event id from barcode
var myclueJSON = '{"eventid":"' + obj.eventid + '","cluesequence":"' + obj.cluesequence + '","lat":"' + clueobj.lat + '","lng":"' + clueobj.lng + '"}';
}//end scanner.scan()
//make AJAX call to save data
$.ajax(
{
url: "http://myurlhere/myfilename.php",
type: 'post',
data:{data:myclueJSON},
success: function(returndata)
{
//process success returndata
},
fail: function(returndata){
//process fail returndata
}
});//end AJAX call to save data
}//end getScan()
//handle current position fetch error
function handle_error(error)
{
switch(error.code)
{
case error.PERMISSION_DENIED:
alert("User denied the request for geolocation. Please allow access to your GPS system when prompted.");
break;
case error.POSITION_UNAVAILABLE:
alert("Location information is unavailable. Check to see if geolocation is enabled on your device.");
break;
case error.TIMEOUT:
alert("The request to get user location timed out. Try moving to a slightly different location to better access the satellite network.");
break;
case error.UNKNOWN_ERROR:
alert("An unknown error occurred. Call tech support at (999) 999-9999.");
break;
}//end error code switch
}//end handle_error()

Nested JSON fetch using jQuery

I am trying to create an RSS Feed kind of Message display from Yammer.
<script type="text/javascript">
var cleanit = null;
$(document).ready(function(){ cleanit = setInterval('callYammer()', 50);});
function callYammer(){
clearInterval(cleanit);
$.getJSON("./yammer.feed?request=messages",function(json) {
var objYammer = $("#yammerFeed");
objYammer.html('');
$.each(json.messages, function(i, m) {
if(!m.replied_to_id && m.body.plain){
var data = "<li>" + m.body.plain;
$.getJSON("./yammer.feed?request=users&userid="+m.sender_id,function(jsonUser) {
//alert(jsonUser.full_name);
data = data + " - "+jsonUser.full_name;
});
data = data + "</li>";
objYammer.append(data);
}
});
});
return false;
}
</script>
I want to display Message along with it's Username.
But in the end, from firebug debugger, what I see is the inner JSON data is not getting appended as I expected.
Though the calls are hitting and data is coming from the call, the
data = " - "+jsonUser.full_name;
is getting executed after all JSON calls for Users.
How do I append Username from inner JSON call to main JSON data?
You call the lines
data = data + "</li>";
objYammer.append(data);
in the code following your inner getJSON AJAX call, but that probably results in these lines being executed before the AJAX request has finished. Put the code INTO the inner AJAX success function to make sure it is fired only after the result is available.
function callYammer(){
clearInterval(cleanit);
$.getJSON("./yammer.feed?request=messages",function(json) {
var objYammer = $("#yammerFeed");
objYammer.html('');
$.each(json.messages, function(i, m) {
if(!m.replied_to_id && m.body.plain){
var data = "<li>" + m.body.plain;
$.getJSON("./yammer.feed?request=users&userid="+m.sender_id,function(jsonUser) {
console.log('1:'+jsonUser.full_name);
data += " - "+jsonUser.full_name + "</li>";
objYammer.append(data);
console.log('2:'+data);
});
}
});
});
Edit:
Just added the console.log() statements. What do they return?

Categories

Resources