Remove asynchronous code into callback in $.each() loop - javascript

In me.getIssuesFromReturnsList the uploadList variable is being returned before the rest of the code executes because it is asynchronous (as per this question)
me.getIssuesFromReturnsList = function () {
var uploadList = [];
$.each(me.returnsList(), function (index, i) {
var issue = issueRepository.GetDefaultIssue();
issue.barcode = i.barcode;
issue.ReturnsAmount(i.amount);
var uploadItem = {
barcode: i.barcode,
amount: i.amount,
issue: ko.observable(issue)
};
uploadList.push(uploadItem);
issueRepository.GetIssuesOffline(i.barcode, function (issues) {
if (issues.length > 0) {
uploadItem.issue(issues[0]);
}
});
});
return uploadList;
}
I want to alter this code so that the calls are no longer asynchronous, and instead waits for all the inner code to execute before returning the uploadList.
I know that I need to add a callback to part of the code so that it will wait for issueRepository.getIssuesOffline to finish, but because this is part of a $.each() loop I am really struggling to see where this callback would go.
(I have asked this as a new question because the answers given in the suggested duplicate answer are generic examples and don't have a $.each() loop in them).
In the comments below, Bergi has asked for the contents of getissuesOffline:
GetIssuesOffline:
GetIssuesOffline: function (barcode, callback) {
var me = this;
issueDatabase.GetIssues(barcode, function (issues) {
me._processIssues(issues);
return callback(issues);
});
}
issueDatabase.getIssues:
GetIssues: function (barcode, callback) {
var me = this;
db.transaction(
function (context) {
var query = "SELECT * FROM issues WHERE barcode LIKE '" + barcode + "%' ORDER BY offSaleDate DESC LIMIT 25";
context.executeSql(query, [], function (context, result) {
var issues = [];
for (var i = 0; i < result.rows.length; i++) {
var issue = result.rows.item(i);
issue.Source = dataSources.Local;
issue.isRanged = issue.isRanged == 1 ? true : false;
issues.push(issue);
}
callback(issues);
}, me.ErrorHandler);
}
, me.ErrorHandler);
}
me.processIssues:
_processIssues: function (issues) {
var me = this;
$.each(issues, function (index, i) {
if (i.issueNumber == null) {
i.issueNumber = '';
}
i.issueNumber = i.issueNumber + '';
i.productNumber = i.productNumber + '';
if (i.issueNumber.length == 1) {
i.issueNumber = '0' + i.issueNumber;
}
i.barcode = parseInt(i.productNumber + '' + i.issueNumber);
i.Status = me.GetIssueStatus(i);
i.supplier = me.GetissueSupplierDetails(i);
i.ReturnsAmount = ko.observable(0);
i.Returns = ko.observable({ totes: [] });
returnsRepository.GetReturn(i.barcode, function (r) {
i.ReturnsAmount(r.amount);
if (r.amount > 0) {
i.Returns(r);
} else {
i.Returns({ totes: [] });
}
});
};
i.RefreshReturnsAmount();
me.IssueDatabase.UpdateIssue(i, function (issue) {
me.IssueDatabase.UpdateIssueLastUpdated(issue);
});
});
}

Related

Only 1 value of 2 values in an array are being returned from function in async/await function calls; getting uncaught promise error

New to writing async/await functions in javascript. I just can't seem to get these async/await keywords in the right place. The following code provides a function maCreateWin911CcsTemplate(executionContext, id) which creates an email record with a template in D365 CRM in which in turn calls another function getNewestLicenseTrackingRecord(executionContext, maId) that returns 2 values in an array I need to insert into the email record template passed through an action.
async function maCreateWin911CcsTemplate(executionContext, id)
{
debugger;
var formContext = executionContext;
var maId = id;
maId = maId.toString().replace("{", "").replace("}", "");
var newestLtRecordSnAndLocation = new Array(2);
newestLtRecordSnAndLocation = getNewestLicenseTrackingRecord(executionContext, maId);
var sn = await newestLtRecordSnAndLocation[0];
var sysLocation = newestLtRecordSnAndLocation[1];
var parameters = {};
parameters.sn = sn;
parameters.sysLocation = sysLocation;
var target = {entityType: "new_maintenancecontract", id: maId};
parameters.entity = target;
parameters.getMetadata = function ()
{
return {
boundParameter: "entity",
operationType: 0,
operationName: "new_MAActionCreateWIN911CCSEmail",
parameterTypes:
{
"sn":
{
"typeName": "Edm.String",
"structuralProperty": 1
},
"sysLocation":
{
"typeName": "Edm.String",
"structuralProperty": 1
},
"entity":
{
"typeName": "new_maintenancecontract",
"structuralProperty": 5
}
},
};
}
Xrm.WebApi.online.execute(parameters).then(
function success(result) {
if(result.ok){
result.json().then(function (results) {
var emailId = results.emailId;
emailId = emailId.substring(61, 97);
Xrm.Utility.openEntityForm("email",emailId);
})
}
else
{
Xrm.Utility.alertDialog("Unknown error occured in ISV code.");
}
},
function (error) {
Xrm.Utility.alertDialog(error.message);
}
);
}
function getNewestLicenseTrackingRecord(executionContext, maId)
{
debugger;
var executionContext = executionContext;
var maId = maId;
maId = maId.toString().replace("{", "").replace("}", "");
parent.Xrm.WebApi.retrieveMultipleRecords("new_license", "?$select=createdon,new_licenseno,new_systemlocation&$filter=_new_maid_value%20eq%20" + '<guid>' + "%20&$top=1&$orderby=createdon%20desc").then(
function success(result) {
for (var i = 0; i < result.entities.length; i++) {
alert(result.entities[i].createdon + " : " + result.entities[i].new_licenseno + " : " + result.entities[i].new_systemlocation);
if(result.entities[i].new_licenseno === null)
{
var licenseNo = "";
}
else
{
var licenseNo = result.entities[i].new_licenseno.toString();
}
if(result.entities[i].new_systemlocation === null)
{
var systemLocation = "";
}
else
{
var systemLocation = result.entities[i].new_systemlocation.toString();
}
var ltArray = new Array(2);
ltArray = [licenseNo, systemLocation];
return ltArray;
//break; // just for code demo
}
},
function(error) {
alert("Error: " + error.message);
}
);
}
As you can see from above, I am returning an array with 2 values in the getNewestLicenseTrackingRecord(executionContext, maId) however, one of the values is always returning undefined because of an uncaught promise as seen below:
I've been fighting with moving the async/await keywords around and have not been successful in getting both values. Any help would be much appreciated.

JavaScript array has elements but length is zero

I've done some searching around the web and nothing seems to solve my problem. I have the following jQuery code:
function youtube_data_parser(data) {
//---> parse video data - start
var qsToJson = function(qs) {
var res = {};
var pars = qs.split('&');
var kv, k, v;
for (i in pars) {
kv = pars[i].split('=');
k = kv[0];
v = kv[1];
res[k] = decodeURIComponent(v);
}
return res;
}
//---> parse video data - end
var get_video_info = qsToJson(data);
if (get_video_info.status == 'fail') {
return {
status: "error",
code: "invalid_url",
msg: "check your url or video id"
};
} else {
// remapping urls into an array of objects
//--->parse > url_encoded_fmt_stream_map > start
//will get the video urls
var tmp = get_video_info["url_encoded_fmt_stream_map"];
if (tmp) {
tmp = tmp.split(',');
for (i in tmp) {
tmp[i] = qsToJson(tmp[i]);
}
get_video_info["url_encoded_fmt_stream_map"] = tmp;
}
//--->parse > url_encoded_fmt_stream_map > end
//--->parse > player_response > start
var tmp1 = get_video_info["player_response"];
if (tmp1) {
get_video_info["player_response"] = JSON.parse(tmp1);
}
//--->parse > player_response > end
//--->parse > keywords > start
var keywords = get_video_info["keywords"];
if (keywords) {
key_words = keywords.replace(/\+/g, ' ').split(',');
for (i in key_words) {
keywords[i] = qsToJson(key_words[i]);
}
get_video_info["keywords"] = {
all: keywords.replace(/\+/g, ' '),
arr: key_words
};
}
//--->parse > keywords > end
//return data
return {
status: 'success',
raw_data: qsToJson(data),
video_info: get_video_info
};
}
}
function getVideoInfo() {
var get_video_url = $('#ytdlUrl').val();
var get_video_id = getUrlVars(get_video_url)['v'];
var video_arr_final = [];
var ajax_url = "video_info.php?id=" + get_video_id;
$.get(ajax_url, function(d1) {
var data = youtube_data_parser(d1);
var video_data = data.video_info;
var player_info = data.video_info.player_response;
var video_title = player_info.videoDetails.title.replace(/\+/g, ' ');
var fmt_list = video_data.fmt_list.split(',');
var video_thumbnail_url = video_data.thumbnail_url;
var video_arr = video_data.url_encoded_fmt_stream_map;
//create video file array
$.each(video_arr, function(i1, v1) {
var valueToPush = {};
valueToPush.video_url = v1.url;
valueToPush.video_thumbnail_url = video_thumbnail_url;
valueToPush.video_title = video_title;
$.each(fmt_list, function(i2, v2) {
var fmt = v2.split('/');
var fmt_id = fmt[0];
var fmt_quality = fmt[1];
if (fmt_id == v1.itag) {
valueToPush.fmt_id = fmt_id;
valueToPush.fmt_quality = fmt_quality;
}
});
video_arr_final.push(valueToPush);
});
});
return video_arr_final;
}
function getUrlVars(url) {
var vars = {};
var parts = url.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m, key, value) {
vars[key] = value;
});
return vars;
}
function fillInOptions(ytOptions) {
//console.log(ytOptions);
//alert(ytOptions[0]);
var ytFill = ytOptions;
console.log(ytFill);
//ytFill.forEach(function(i,v) {
var ytdlOptions = $('#ytdlOptions');
ytFill.forEach(function(i,v) {
console.log(i);
ytdlOptions.append(new Option(v.fmt_quality, v.fmt_id));
});
return true;
}
function showYTDLLoader() {
$('#ytdlInput').fadeOut(1000, function() {
$('#ytdlLoader').fadeIn(500);
});
var options = getVideoInfo();
//console.log(options);
if (fillInOptions(options) == true) {
//do rest
}
}
function showYTDLOptions() {
return true;
}
function startDownload() {
showYTDLLoader();
}
function hideYTDLLoader() {
$('#ytdlLoader').fadeOut(500);
}
function animateCSS(element, animationName, callback) {
const node = $(element);
node.addClass(animationName);
function handleAnimationEnd() {
node.removeClass(animationName);
node.animationend = null;
if (typeof callback === 'function') callback();
}
node.animationend = handleAnimationEnd();
}
When my button is clicked, I call showYTDLLoader() which gets an array of objects from the YouTube API that looks like this:
[
{
"video_url": "https://r7---sn-uxanug5-cox6.googlevideo.com/videoplayback?expire=1572496003&ei=Iw66Xa24H8PL3LUPiN25mAs&ip=2001%3A8003%3A749b%3Aa01%3A5cd8%3Ac610%3A6402%3Ad0fe&id=o-ADsVnoOoBQ6-SWzYZU7gHES06s7xQptJG6hn9WcakITY&itag=22&source=youtube&requiressl=yes&mm=31%2C29&mn=sn-uxanug5-cox6%2Csn-ntqe6n7r&ms=au%2Crdu&mv=m&mvi=6&pl=39&initcwndbps=1655000&mime=video%2Fmp4&ratebypass=yes&dur=917.768&lmt=1572418007364260&mt=1572474311&fvip=4&fexp=23842630&c=WEB&txp=5535432&sparams=expire%2Cei%2Cip%2Cid%2Citag%2Csource%2Crequiressl%2Cmime%2Cratebypass%2Cdur%2Clmt&sig=ALgxI2wwRgIhAIp-4gyUTLoXFetbY0ha_YnR7DJqsp_MNjjIxqDdfPZJAiEA_WPd21jgX9broBcigf8rcSEVoJb2_NX7t3XZQqytsSM%3D&lsparams=mm%2Cmn%2Cms%2Cmv%2Cmvi%2Cpl%2Cinitcwndbps&lsig=AHylml4wRAIgacvP3zjEq-rVEZFrX7a_hC6TR-Zab7Ii-Fbaupjs_PcCIHdZht4l4ioYL3ERz7WNiSbnOnhm5iYxEECaQXPP2hUp",
"video_title": "Arnold Schwarzenegger on Son-in-law Chris Pratt, Pranking Sylvester Stallone & Terminator’s Return",
"fmt_id": "22",
"fmt_quality": "1280x720"
},
{
"video_url": "https://r7---sn-uxanug5-cox6.googlevideo.com/videoplayback?expire=1572496003&ei=Iw66Xa24H8PL3LUPiN25mAs&ip=2001%3A8003%3A749b%3Aa01%3A5cd8%3Ac610%3A6402%3Ad0fe&id=o-ADsVnoOoBQ6-SWzYZU7gHES06s7xQptJG6hn9WcakITY&itag=18&source=youtube&requiressl=yes&mm=31%2C29&mn=sn-uxanug5-cox6%2Csn-ntqe6n7r&ms=au%2Crdu&mv=m&mvi=6&pl=39&initcwndbps=1655000&mime=video%2Fmp4&gir=yes&clen=44248820&ratebypass=yes&dur=917.768&lmt=1572416976690256&mt=1572474311&fvip=4&fexp=23842630&c=WEB&txp=5531432&sparams=expire%2Cei%2Cip%2Cid%2Citag%2Csource%2Crequiressl%2Cmime%2Cgir%2Cclen%2Cratebypass%2Cdur%2Clmt&sig=ALgxI2wwRQIhANTZJlBHFWQWCnfK11yvLiPUV26c6NzvqIMKjDwmsByMAiBUSy0ZJMo4GdHSiRU4xBDDLxLtzwKZAqAKCiB-1aViDQ%3D%3D&lsparams=mm%2Cmn%2Cms%2Cmv%2Cmvi%2Cpl%2Cinitcwndbps&lsig=AHylml4wRAIgacvP3zjEq-rVEZFrX7a_hC6TR-Zab7Ii-Fbaupjs_PcCIHdZht4l4ioYL3ERz7WNiSbnOnhm5iYxEECaQXPP2hUp",
"video_title": "Arnold Schwarzenegger on Son-in-law Chris Pratt, Pranking Sylvester Stallone & Terminator’s Return",
"fmt_id": "18",
"fmt_quality": "640x360"
}
]
But when I try and loop through each entry with fillInOptions(), my loop is never completed because the length is apparently zero. However, when I dump the array using console.log() it tells me the length is 2, and displays the above. I need to be able to add each option to my dropdown.
Thankyou!
UPDATE: Added full code, sorry!
It looks like your .forEach() is the root of the problem. The parameters of a forEach are currentValue, index like this: array.forEach(function(currentValue, index) {}); but it looks like you're using them in the opposite way
Try rewriting that iteration to this:
ytFill.forEach(function(v, i) {
console.log(i);
ytdlOptions.append(new Option(v.fmt_quality, v.fmt_id));
});
Notice the difference in the order of v and i in the parameters.

function keeps returning undefined array using Async Await

Can't get my getJSON function to return the array. I've been trying to use await/async but I'm doing something wrong.
.map and .filter should be synchronous but I've tried putting await on them as well.
$(function() {
$("#roll").click(async function() {
var x = await getTreasure()
chrome.extension.getBackgroundPage().console.log(x)
});
});
function getTreasure() {
var sizeValue = $('input[name=size]:checked').val();
var crValue = $('input[name=challenge]:checked').val();
var die = Math.floor((Math.random() * 100) + 1);
var url = "";
if (sizeValue == "individual") {
url = chrome.runtime.getURL("treasure_individual.json");
} else {
url = chrome.runtime.getURL("treasure_horde.json");
};
$.getJSON(url, function(data) {
var match = data.treasure.filter(function (e) {
return e.cr == crValue;
});
for (i in match[0].roll) {
var str = match[0].roll[i].d100;
var arr = str.match(/([0-9]+)/g);
var levels = $.map(arr, function (x) {
return parseInt(x, 10);
});
if (die == levels[0] || die >= levels[0] && die <= levels[1]) {
chrome.extension.getBackgroundPage().console.log(levels);
return levels;
} else {
return die;
};
};
});
};
Edit:
Ok, didn't understand await still needed a Promise. But I'm still not getting it. Tried adding the return Promise around the getJson function but it's still not returning levels.
function getTreasure() {
var sizeValue = $('input[name=size]:checked').val();
var crValue = $('input[name=challenge]:checked').val();
var die = Math.floor((Math.random() * 100) + 1);
var url = "";
if (sizeValue == "individual") {
url = chrome.runtime.getURL("treasure_individual.json");
} else {
url = chrome.runtime.getURL("treasure_horde.json");
};
return new Promise(resolve => {
$.getJSON(url, function(data) {
var match = data.treasure.filter(function (e) {
return e.cr == crValue;
});
for (i in match[0].roll) {
var str = match[0].roll[i].d100;
var arr = str.match(/([0-9]+)/g);
var levels = $.map(arr, function (x) {
return parseInt(x, 10);
});
if (die == levels[0] || die >= levels[0] && die <= levels[1]) {
//chrome.extension.getBackgroundPage().console.log(levels);
return levels;
};
};
});
});
};
The way to return the promise is not by adding new Promise (which is an anti-pattern in this case), but to get the promise that jQuery already has for you:
return $.getJSON(url, function(data) {
// ^^^^^^
// .......
}).promise();
// ^^^^^^^^^^
NB: in your second attempt you never called resolve.
If you need some specific data to be "promised", then chain a then instead of using the callback of $.getJSON. Like this:
return $.getJSON(url).then(function(data) {
// ^^^^^^ ^^^^^^
// .......
return levels;
});

Javascript Callback in for Loop

My problem is that I'm having a Function A which calls at one point another function, let's call it Function B (getChildContent) and needs the return value of Function B in order to proceed. I know that it's because of Javascripts Asynchronous Nature, and i tried to solve it with a callback. But i can't get it work properly.
FunctionA(){
//some Code.....
else {
for(i in clustertitles) {
if(S(text).contains(clustertitles[i])) {
var parent = {};
parent.ClusterName = clustertitles[i];
parent.Functions = [];
var str = '== ' + clustertitles[i] + ' ==\n* ';
str = S(text).between(str,'.').s;
var caps = parseFunctions(str);
for(y in caps) {
//var content = getChildContent(caps[y]);
getChildContent(caps[y], function(content) { //Function call
var child = {};
child.FunctionName = caps[y];
child.Content = [];
child.Content.push(content);
parent.Functions.push(child);
console.log(content);
});
}}}
}
function getChildContent (capname, callback) {
t = capname.replace(' ', '_');
bot.page(t).complete(function (title, text, date) {
var str = S(text).between('== Kurzbeschreibung ==\n* ', '.').s;
if(str === undefined || str === null || str === '') {
throw new Error('Undefined, Null or Empty!');
}
else {
var content = {};
str = parseTitles(str);
content.Owner = str[0];
content.Aim = str[1];
content.What = str[2];
content.Who = str[3];
content.Steps = str[4];
content.Page = 'some URL';
callback(content);
}
});
}
So in Function A I'm trying to call getChildContent from a for-Loop and pass the current string from caps-array. For each String in caps-array getChildContent() makes a http request over a node.js module and retrieves a string. With this string i'm building an object (content) which is needed in Function A to continue. However the 'console.log(content)' in Function A just prints out the object which is created with the last string in caps-array, but for many times. E.G. if caps-array has 5 entries, i get 5 times the object which is created with the last entry of caps-array.
How can i manage the loop/callback to get every time the right object on my console?
Your loop should call another function that preserves the value of y, something like this:
FunctionA(){
//some Code.....
else {
for(i in clustertitles) {
if(S(text).contains(clustertitles[i])) {
var parent = {};
parent.ClusterName = clustertitles[i];
parent.Functions = [];
var str = '== ' + clustertitles[i] + ' ==\n* ';
str = S(text).between(str,'.').s;
var caps = parseFunctions(str);
for(y in caps) {
yourNewFunction (y, caps, parent);
}}}
}
function yourNewFunction (y, caps, parent) {
getChildContent(caps[y], function(content) { //Function call
var child = {};
child.FunctionName = caps[y];
child.Content = [];
child.Content.push(content);
parent.Functions.push(child);
console.log(content);
});
}
function getChildContent (capname, callback) {
t = capname.replace(' ', '_');
bot.page(t).complete(function (title, text, date) {
var str = S(text).between('== Kurzbeschreibung ==\n* ', '.').s;
if(str === undefined || str === null || str === '') {
throw new Error('Undefined, Null or Empty!');
}
else {
var content = {};
str = parseTitles(str);
content.Owner = str[0];
content.Aim = str[1];
content.What = str[2];
content.Who = str[3];
content.Steps = str[4];
content.Page = 'some URL';
callback(content);
}
});
}
There are 2 ways to do so.
Put the loop inside a function, execute your callback after the loop is done. (Problematic if you are doing async call inside the loop.
function doLoopdiloopStuff() {
for() {
}
callback();
}
The other way, the way i prefer looks like this:
for(var i = 0; i < stuff || function(){ /* here's the callback */ }(), false; i++) {
/* do your loop-di-loop */
}
In another example:
for (var index = 0; index < caps.length || function(){ callbackFunction(); /* This is the callback you are calling */ return false;}(); index++) {
var element = caps[index];
// here comes the code of what you want to do with a single element
}

Why are my properties assigning incorrectly?

I created an ObservablePropertyList which is supposed to execute a callback when a property changes. The implementation is:
function ObservablePropertyList(nameCallbackCollection) {
var propertyList = {};
for (var index in nameCallbackCollection) {
var private_value = {};
propertyList["get_" + index] = function () { return private_value; }
propertyList["set_" + index] = function (value) {
// Set the value
private_value = value;
// Invoke the callback
nameCallbackCollection[index](value);
}
}
return propertyList;
}
And here's a quick test demonstration:
var boundProperties = BoundPropertyList({
TheTime: function (value) {
$('#thetime').text(value);
},
TheDate: function (value) {
$('#thedate').text(value);
}
});
var number = 0;
setInterval(function () {
boundProperties.set_TheTime(new Date());
boundProperties.set_TheDate(number++);
}, 500);
For some reason though, the properties are not being assigned correctly or something. That is, calling set_TheTime for some reason executes the callback for set_TheDate, almost as though it were binding everything to only the last item in the list. I can't for the life of me figure out what I'm doing wrong.
When using loops like that you need to wrap it in an enclosure
function ObservablePropertyList(nameCallbackCollection) {
var propertyList = {};
for (var index in nameCallbackCollection) {
(function(target){
var private_value = {};
propertyList["get_" + index] = function () { return private_value; }
propertyList["set_" + index] = function (value) {
// Set the value
private_value = value;
// Invoke the callback
target(value);
}
})(nameCallbackCollection[index]);
}
return propertyList;
}
You need to create a closure in order for each iteration of the for loop to have its own private_variable object. Otherwise, each iteration just overwrites the previous (since private_variable is hoisted to the top of its scope). I'd set it up like this:
var ObservablePropertyList = (function () {
"use strict";
var handleAccess = function (propList, key, callback) {
var privValue = {};
propList["get_" + key] = function () {
return privValue;
};
propList["set_" + key] = function (value) {
// Set the value
privValue = value;
// Invoke the callback
callback(value);
};
};
return function (coll) {
var propertyList = {}, index;
for (index in coll) {
handleAccess(propertyList, index, coll[index]);
}
return propertyList;
};
}());
var boundProperties = ObservablePropertyList({
TheTime: function (value) {
$('#thetime').text(value);
},
TheDate: function (value) {
$('#thedate').text(value);
}
}), number = 0;
setInterval(function () {
boundProperties.set_TheTime(new Date());
boundProperties.set_TheDate(number++);
}, 500);
DEMO: http://jsfiddle.net/PXHDT/

Categories

Resources