问题
I don't understand why i can't affect my global variable. I don't understand why this doesn't work.. I believe that it has to do with SDK.REST.retriveMultipleRecords, but i dont understand how. As you can see in first alert it works. but in 2nd it shows as "Undefined". In this fiddle, i have a simple example about defining a global variable and it works.
Can anyone help with this issue? Why it is not affecting my globalVar?
Players = new Array(); //GLOBAL VAR
function setPlayers(topNumber){
SDK.REST.retrieveMultipleRecords(
"gamify_utilizador",
"$select=gamify_utilizadorId,gamify_name,gamify_Ranking&$top="+topNumber+"&$orderby=gamify_Ranking asc",
function (results) {
if(results.length > 0){
for(var i = 0;i<results.length;i++){
Players.push(new Array(results[i].gamify_utilizadorId, results[i].gamify_name));
alert(Players[i]); // ALERT OK
}
}
else {
alert("No Contact records are available to set as the primary contact for the account.");
}
},
errorHandler,
function () {
//OnComplete handler
}
)
alert(Players[1]); // Alert says "Undefined"
};
document.onreadystatechange = function () {
if (document.readyState == "complete") {
setPlayers(4);
alert(Players[1]);
}
}
回答1:
Instead of alert(Players[1]);
try this alert(Players[0]);
回答2:
Your data is retrieved asynchronously, so it is available at some time after the setPlayers function is executed, and thus some time after the alert(Players[1])
runs.
Here is some code that verifies it:
setTimeout(function(){ alert(Players[1]) }, 3000); // check the variable after 3 seconds
You need to use the data after the success handler (the function which populates the Players array) executes. You could look into the Promises pattern that offers a more traditional interface to asynchronous programming.
回答3:
think it should be because the inner function has not yet been performed, and thus the array still contains no value at position 1, just after the execution and completion of this array will value this available
来源:https://stackoverflow.com/questions/22040689/javascript-global-var-doesnt-work-using-sdk-rest-retrivemultiplerecords