Javascript code executing out of order, can I fix it?












2















I am trying to get this piece of code to work and it seems to be running out of order. I noticed this in the console logs.






<script>
var wrapper = document.getElementById("myHTMLWrapper");
var myHTML = '';
var databaseRef = firebase.database().ref('items/');
databaseRef.once('value', function(snapshot)
{
snapshot.forEach(function(childSnapshot)
{
var childKey = childSnapshot.key;
var childData = childSnapshot.val();
myHTML += '<div class="card">';
myHTML += '<div class="card-body">';
var urlimage = '';
storageRef.child('images/'+ childData.id +'.jpg').getDownloadURL().then(function(url){
urlimage = url;
console.log(urlimage);
});
console.log('url outside of function is: '+urlimage);
myHTML += '<img src="'+ urlimage +'" class="img-thumbnail" height="">';
console.log('images/'+ childData.id +'.jpg');
myHTML += '<h4>'+ childData.sku + ' - ' + childData.name +'</h4>';
myHTML += '</div>';
myHTML += '</div>';
});
wrapper.innerHTML = myHTML;
});
</script>





It seems that the code is running console.log('url outside of function is: '+urlimage); before it runs console.log(urlimage);



I am not too familiar with Javascript yet and I hope I can get some help with this one.



Thanks!!!










share|improve this question


















  • 1





    It's because of async! Use another .then()

    – Bhojendra Rauniyar
    Nov 25 '18 at 21:21


















2















I am trying to get this piece of code to work and it seems to be running out of order. I noticed this in the console logs.






<script>
var wrapper = document.getElementById("myHTMLWrapper");
var myHTML = '';
var databaseRef = firebase.database().ref('items/');
databaseRef.once('value', function(snapshot)
{
snapshot.forEach(function(childSnapshot)
{
var childKey = childSnapshot.key;
var childData = childSnapshot.val();
myHTML += '<div class="card">';
myHTML += '<div class="card-body">';
var urlimage = '';
storageRef.child('images/'+ childData.id +'.jpg').getDownloadURL().then(function(url){
urlimage = url;
console.log(urlimage);
});
console.log('url outside of function is: '+urlimage);
myHTML += '<img src="'+ urlimage +'" class="img-thumbnail" height="">';
console.log('images/'+ childData.id +'.jpg');
myHTML += '<h4>'+ childData.sku + ' - ' + childData.name +'</h4>';
myHTML += '</div>';
myHTML += '</div>';
});
wrapper.innerHTML = myHTML;
});
</script>





It seems that the code is running console.log('url outside of function is: '+urlimage); before it runs console.log(urlimage);



I am not too familiar with Javascript yet and I hope I can get some help with this one.



Thanks!!!










share|improve this question


















  • 1





    It's because of async! Use another .then()

    – Bhojendra Rauniyar
    Nov 25 '18 at 21:21
















2












2








2








I am trying to get this piece of code to work and it seems to be running out of order. I noticed this in the console logs.






<script>
var wrapper = document.getElementById("myHTMLWrapper");
var myHTML = '';
var databaseRef = firebase.database().ref('items/');
databaseRef.once('value', function(snapshot)
{
snapshot.forEach(function(childSnapshot)
{
var childKey = childSnapshot.key;
var childData = childSnapshot.val();
myHTML += '<div class="card">';
myHTML += '<div class="card-body">';
var urlimage = '';
storageRef.child('images/'+ childData.id +'.jpg').getDownloadURL().then(function(url){
urlimage = url;
console.log(urlimage);
});
console.log('url outside of function is: '+urlimage);
myHTML += '<img src="'+ urlimage +'" class="img-thumbnail" height="">';
console.log('images/'+ childData.id +'.jpg');
myHTML += '<h4>'+ childData.sku + ' - ' + childData.name +'</h4>';
myHTML += '</div>';
myHTML += '</div>';
});
wrapper.innerHTML = myHTML;
});
</script>





It seems that the code is running console.log('url outside of function is: '+urlimage); before it runs console.log(urlimage);



I am not too familiar with Javascript yet and I hope I can get some help with this one.



Thanks!!!










share|improve this question














I am trying to get this piece of code to work and it seems to be running out of order. I noticed this in the console logs.






<script>
var wrapper = document.getElementById("myHTMLWrapper");
var myHTML = '';
var databaseRef = firebase.database().ref('items/');
databaseRef.once('value', function(snapshot)
{
snapshot.forEach(function(childSnapshot)
{
var childKey = childSnapshot.key;
var childData = childSnapshot.val();
myHTML += '<div class="card">';
myHTML += '<div class="card-body">';
var urlimage = '';
storageRef.child('images/'+ childData.id +'.jpg').getDownloadURL().then(function(url){
urlimage = url;
console.log(urlimage);
});
console.log('url outside of function is: '+urlimage);
myHTML += '<img src="'+ urlimage +'" class="img-thumbnail" height="">';
console.log('images/'+ childData.id +'.jpg');
myHTML += '<h4>'+ childData.sku + ' - ' + childData.name +'</h4>';
myHTML += '</div>';
myHTML += '</div>';
});
wrapper.innerHTML = myHTML;
});
</script>





It seems that the code is running console.log('url outside of function is: '+urlimage); before it runs console.log(urlimage);



I am not too familiar with Javascript yet and I hope I can get some help with this one.



Thanks!!!






<script>
var wrapper = document.getElementById("myHTMLWrapper");
var myHTML = '';
var databaseRef = firebase.database().ref('items/');
databaseRef.once('value', function(snapshot)
{
snapshot.forEach(function(childSnapshot)
{
var childKey = childSnapshot.key;
var childData = childSnapshot.val();
myHTML += '<div class="card">';
myHTML += '<div class="card-body">';
var urlimage = '';
storageRef.child('images/'+ childData.id +'.jpg').getDownloadURL().then(function(url){
urlimage = url;
console.log(urlimage);
});
console.log('url outside of function is: '+urlimage);
myHTML += '<img src="'+ urlimage +'" class="img-thumbnail" height="">';
console.log('images/'+ childData.id +'.jpg');
myHTML += '<h4>'+ childData.sku + ' - ' + childData.name +'</h4>';
myHTML += '</div>';
myHTML += '</div>';
});
wrapper.innerHTML = myHTML;
});
</script>





<script>
var wrapper = document.getElementById("myHTMLWrapper");
var myHTML = '';
var databaseRef = firebase.database().ref('items/');
databaseRef.once('value', function(snapshot)
{
snapshot.forEach(function(childSnapshot)
{
var childKey = childSnapshot.key;
var childData = childSnapshot.val();
myHTML += '<div class="card">';
myHTML += '<div class="card-body">';
var urlimage = '';
storageRef.child('images/'+ childData.id +'.jpg').getDownloadURL().then(function(url){
urlimage = url;
console.log(urlimage);
});
console.log('url outside of function is: '+urlimage);
myHTML += '<img src="'+ urlimage +'" class="img-thumbnail" height="">';
console.log('images/'+ childData.id +'.jpg');
myHTML += '<h4>'+ childData.sku + ' - ' + childData.name +'</h4>';
myHTML += '</div>';
myHTML += '</div>';
});
wrapper.innerHTML = myHTML;
});
</script>






javascript html






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 25 '18 at 21:12









J WJ W

135




135








  • 1





    It's because of async! Use another .then()

    – Bhojendra Rauniyar
    Nov 25 '18 at 21:21
















  • 1





    It's because of async! Use another .then()

    – Bhojendra Rauniyar
    Nov 25 '18 at 21:21










1




1





It's because of async! Use another .then()

– Bhojendra Rauniyar
Nov 25 '18 at 21:21







It's because of async! Use another .then()

– Bhojendra Rauniyar
Nov 25 '18 at 21:21














3 Answers
3






active

oldest

votes


















2














storageRef.child('images/'+ childData.id +'.jpg').getDownloadURL().then(function(url){
urlimage = url;
console.log(urlimage);
});


The piece of code above from the code you provided actually uses Promises. You usually use promises when dealing with asynchronous data, for example, data from a server. While that piece of code is processing, other lines of code are being executed, thereby leading to what you are observing. The behavior of asynchronous code cannot be usually predicted.



To use urlimage you can do something like this.



storageRef.child('images/'+ childData.id +'.jpg').getDownloadURL().then(function(url){
myHTML += '<img src="'+ url +'" class="img-thumbnail" height="">';
});





share|improve this answer
























  • Thank you. I just tried your solution but it seems that now it just skips the myHTML += '<img src="'+ url +'" class="img-thumbnail" height="">'; until the end. Is there any way I can wait for the promise to resolve before proceeding?

    – J W
    Nov 25 '18 at 21:38













  • You can also include the other lines of codes too. Those beginning with myHTML += inside the promise's function

    – zeze
    Nov 25 '18 at 21:51













  • Thanks. I've done that and not it seems to delay the entire myHTML string concatenation to a point where wrapper.innerHTML is storing an empty myHTML. Is there anything I can do to delay the execution of the rest of the javascript code? Thanks a bunch for your time and expertise.

    – J W
    Nov 25 '18 at 22:01











  • You could delay the execution using setTimeout but that is definitely not the right way to go. I think the whole code needs restructuring but I cannot figure out how to do that yet especially with the fact that I'm not so familiar with firebase.

    – zeze
    Nov 25 '18 at 22:41



















1














You have asynchronous code here. Looks like getDownloadURL() is a promise. I don't know what that function do (google says it is from firebase), but it comes from external library. And it can take some time to execute.



Even if it takes few milliseconds. It is always moved at the end of event loop.






share|improve this answer
























  • the wording always doesn't suit with async.

    – Bhojendra Rauniyar
    Nov 25 '18 at 21:23











  • Thank you for answering. That does seem to be the issue. Is there any way I can wait for the callback function to resolve before proceeding?

    – J W
    Nov 25 '18 at 21:33



















1














getDownloadURL().then(...) looks like an asynchronous function to me. Asynchronous (async for short) means that the javascript makes an external request (e.g. download a file) and then executes a callback function (the argument to then) once the external request is complete. In general you should expect javascript async callbacks to execute after the entire function call stack that starts the request.



Most programming languages with asynchronous functions will have a facility to wait, which is often called "blocking", but Javascript is an exception.



The reason Javascript does not permit blocking is Javascript engines are single threaded, so blocking on an operation blocks the whole system.



So for a long time, couldn't block a function to wait for the async calls to finish and pick up as if they were ordinary synchronous calls.



This is so inconvenient, Javascript eventually introduced async functions and the await keyword, which does what you want.



async function buildHtml(snapshot) {
// Note the novel for-loop syntax. The inner function in forEach would break async.
for(childSnapshot of snapshot) {
var childKey = childSnapshot.key;
var childData = childSnapshot.val();
myHTML += '<div class="card">';
myHTML += '<div class="card-body">';
var urlimage = await storageRef.child('images/'+ childData.id +'.jpg').getDownloadURL(); // global state may change here
myHTML += '<img src="'+ urlimage +'" class="img-thumbnail" height="">';
myHTML += '<h4>'+ childData.sku + ' - ' + childData.name +'</h4>';
myHTML += '</div>';
myHTML += '</div>';
}
wrapper.innerHTML = myHTML;
}





share|improve this answer


























  • Thank you for answering. That does seem to be the issue. Is there any way I can wait for the callback function to resolve before proceeding?

    – J W
    Nov 25 '18 at 21:33











  • @JW yes, await. It's new, surprisingly.

    – 01d55
    Nov 28 '18 at 4:58











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53472038%2fjavascript-code-executing-out-of-order-can-i-fix-it%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























3 Answers
3






active

oldest

votes








3 Answers
3






active

oldest

votes









active

oldest

votes






active

oldest

votes









2














storageRef.child('images/'+ childData.id +'.jpg').getDownloadURL().then(function(url){
urlimage = url;
console.log(urlimage);
});


The piece of code above from the code you provided actually uses Promises. You usually use promises when dealing with asynchronous data, for example, data from a server. While that piece of code is processing, other lines of code are being executed, thereby leading to what you are observing. The behavior of asynchronous code cannot be usually predicted.



To use urlimage you can do something like this.



storageRef.child('images/'+ childData.id +'.jpg').getDownloadURL().then(function(url){
myHTML += '<img src="'+ url +'" class="img-thumbnail" height="">';
});





share|improve this answer
























  • Thank you. I just tried your solution but it seems that now it just skips the myHTML += '<img src="'+ url +'" class="img-thumbnail" height="">'; until the end. Is there any way I can wait for the promise to resolve before proceeding?

    – J W
    Nov 25 '18 at 21:38













  • You can also include the other lines of codes too. Those beginning with myHTML += inside the promise's function

    – zeze
    Nov 25 '18 at 21:51













  • Thanks. I've done that and not it seems to delay the entire myHTML string concatenation to a point where wrapper.innerHTML is storing an empty myHTML. Is there anything I can do to delay the execution of the rest of the javascript code? Thanks a bunch for your time and expertise.

    – J W
    Nov 25 '18 at 22:01











  • You could delay the execution using setTimeout but that is definitely not the right way to go. I think the whole code needs restructuring but I cannot figure out how to do that yet especially with the fact that I'm not so familiar with firebase.

    – zeze
    Nov 25 '18 at 22:41
















2














storageRef.child('images/'+ childData.id +'.jpg').getDownloadURL().then(function(url){
urlimage = url;
console.log(urlimage);
});


The piece of code above from the code you provided actually uses Promises. You usually use promises when dealing with asynchronous data, for example, data from a server. While that piece of code is processing, other lines of code are being executed, thereby leading to what you are observing. The behavior of asynchronous code cannot be usually predicted.



To use urlimage you can do something like this.



storageRef.child('images/'+ childData.id +'.jpg').getDownloadURL().then(function(url){
myHTML += '<img src="'+ url +'" class="img-thumbnail" height="">';
});





share|improve this answer
























  • Thank you. I just tried your solution but it seems that now it just skips the myHTML += '<img src="'+ url +'" class="img-thumbnail" height="">'; until the end. Is there any way I can wait for the promise to resolve before proceeding?

    – J W
    Nov 25 '18 at 21:38













  • You can also include the other lines of codes too. Those beginning with myHTML += inside the promise's function

    – zeze
    Nov 25 '18 at 21:51













  • Thanks. I've done that and not it seems to delay the entire myHTML string concatenation to a point where wrapper.innerHTML is storing an empty myHTML. Is there anything I can do to delay the execution of the rest of the javascript code? Thanks a bunch for your time and expertise.

    – J W
    Nov 25 '18 at 22:01











  • You could delay the execution using setTimeout but that is definitely not the right way to go. I think the whole code needs restructuring but I cannot figure out how to do that yet especially with the fact that I'm not so familiar with firebase.

    – zeze
    Nov 25 '18 at 22:41














2












2








2







storageRef.child('images/'+ childData.id +'.jpg').getDownloadURL().then(function(url){
urlimage = url;
console.log(urlimage);
});


The piece of code above from the code you provided actually uses Promises. You usually use promises when dealing with asynchronous data, for example, data from a server. While that piece of code is processing, other lines of code are being executed, thereby leading to what you are observing. The behavior of asynchronous code cannot be usually predicted.



To use urlimage you can do something like this.



storageRef.child('images/'+ childData.id +'.jpg').getDownloadURL().then(function(url){
myHTML += '<img src="'+ url +'" class="img-thumbnail" height="">';
});





share|improve this answer













storageRef.child('images/'+ childData.id +'.jpg').getDownloadURL().then(function(url){
urlimage = url;
console.log(urlimage);
});


The piece of code above from the code you provided actually uses Promises. You usually use promises when dealing with asynchronous data, for example, data from a server. While that piece of code is processing, other lines of code are being executed, thereby leading to what you are observing. The behavior of asynchronous code cannot be usually predicted.



To use urlimage you can do something like this.



storageRef.child('images/'+ childData.id +'.jpg').getDownloadURL().then(function(url){
myHTML += '<img src="'+ url +'" class="img-thumbnail" height="">';
});






share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 25 '18 at 21:31









zezezeze

236




236













  • Thank you. I just tried your solution but it seems that now it just skips the myHTML += '<img src="'+ url +'" class="img-thumbnail" height="">'; until the end. Is there any way I can wait for the promise to resolve before proceeding?

    – J W
    Nov 25 '18 at 21:38













  • You can also include the other lines of codes too. Those beginning with myHTML += inside the promise's function

    – zeze
    Nov 25 '18 at 21:51













  • Thanks. I've done that and not it seems to delay the entire myHTML string concatenation to a point where wrapper.innerHTML is storing an empty myHTML. Is there anything I can do to delay the execution of the rest of the javascript code? Thanks a bunch for your time and expertise.

    – J W
    Nov 25 '18 at 22:01











  • You could delay the execution using setTimeout but that is definitely not the right way to go. I think the whole code needs restructuring but I cannot figure out how to do that yet especially with the fact that I'm not so familiar with firebase.

    – zeze
    Nov 25 '18 at 22:41



















  • Thank you. I just tried your solution but it seems that now it just skips the myHTML += '<img src="'+ url +'" class="img-thumbnail" height="">'; until the end. Is there any way I can wait for the promise to resolve before proceeding?

    – J W
    Nov 25 '18 at 21:38













  • You can also include the other lines of codes too. Those beginning with myHTML += inside the promise's function

    – zeze
    Nov 25 '18 at 21:51













  • Thanks. I've done that and not it seems to delay the entire myHTML string concatenation to a point where wrapper.innerHTML is storing an empty myHTML. Is there anything I can do to delay the execution of the rest of the javascript code? Thanks a bunch for your time and expertise.

    – J W
    Nov 25 '18 at 22:01











  • You could delay the execution using setTimeout but that is definitely not the right way to go. I think the whole code needs restructuring but I cannot figure out how to do that yet especially with the fact that I'm not so familiar with firebase.

    – zeze
    Nov 25 '18 at 22:41

















Thank you. I just tried your solution but it seems that now it just skips the myHTML += '<img src="'+ url +'" class="img-thumbnail" height="">'; until the end. Is there any way I can wait for the promise to resolve before proceeding?

– J W
Nov 25 '18 at 21:38







Thank you. I just tried your solution but it seems that now it just skips the myHTML += '<img src="'+ url +'" class="img-thumbnail" height="">'; until the end. Is there any way I can wait for the promise to resolve before proceeding?

– J W
Nov 25 '18 at 21:38















You can also include the other lines of codes too. Those beginning with myHTML += inside the promise's function

– zeze
Nov 25 '18 at 21:51







You can also include the other lines of codes too. Those beginning with myHTML += inside the promise's function

– zeze
Nov 25 '18 at 21:51















Thanks. I've done that and not it seems to delay the entire myHTML string concatenation to a point where wrapper.innerHTML is storing an empty myHTML. Is there anything I can do to delay the execution of the rest of the javascript code? Thanks a bunch for your time and expertise.

– J W
Nov 25 '18 at 22:01





Thanks. I've done that and not it seems to delay the entire myHTML string concatenation to a point where wrapper.innerHTML is storing an empty myHTML. Is there anything I can do to delay the execution of the rest of the javascript code? Thanks a bunch for your time and expertise.

– J W
Nov 25 '18 at 22:01













You could delay the execution using setTimeout but that is definitely not the right way to go. I think the whole code needs restructuring but I cannot figure out how to do that yet especially with the fact that I'm not so familiar with firebase.

– zeze
Nov 25 '18 at 22:41





You could delay the execution using setTimeout but that is definitely not the right way to go. I think the whole code needs restructuring but I cannot figure out how to do that yet especially with the fact that I'm not so familiar with firebase.

– zeze
Nov 25 '18 at 22:41













1














You have asynchronous code here. Looks like getDownloadURL() is a promise. I don't know what that function do (google says it is from firebase), but it comes from external library. And it can take some time to execute.



Even if it takes few milliseconds. It is always moved at the end of event loop.






share|improve this answer
























  • the wording always doesn't suit with async.

    – Bhojendra Rauniyar
    Nov 25 '18 at 21:23











  • Thank you for answering. That does seem to be the issue. Is there any way I can wait for the callback function to resolve before proceeding?

    – J W
    Nov 25 '18 at 21:33
















1














You have asynchronous code here. Looks like getDownloadURL() is a promise. I don't know what that function do (google says it is from firebase), but it comes from external library. And it can take some time to execute.



Even if it takes few milliseconds. It is always moved at the end of event loop.






share|improve this answer
























  • the wording always doesn't suit with async.

    – Bhojendra Rauniyar
    Nov 25 '18 at 21:23











  • Thank you for answering. That does seem to be the issue. Is there any way I can wait for the callback function to resolve before proceeding?

    – J W
    Nov 25 '18 at 21:33














1












1








1







You have asynchronous code here. Looks like getDownloadURL() is a promise. I don't know what that function do (google says it is from firebase), but it comes from external library. And it can take some time to execute.



Even if it takes few milliseconds. It is always moved at the end of event loop.






share|improve this answer













You have asynchronous code here. Looks like getDownloadURL() is a promise. I don't know what that function do (google says it is from firebase), but it comes from external library. And it can take some time to execute.



Even if it takes few milliseconds. It is always moved at the end of event loop.







share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 25 '18 at 21:22









kotletkotlet

16218




16218













  • the wording always doesn't suit with async.

    – Bhojendra Rauniyar
    Nov 25 '18 at 21:23











  • Thank you for answering. That does seem to be the issue. Is there any way I can wait for the callback function to resolve before proceeding?

    – J W
    Nov 25 '18 at 21:33



















  • the wording always doesn't suit with async.

    – Bhojendra Rauniyar
    Nov 25 '18 at 21:23











  • Thank you for answering. That does seem to be the issue. Is there any way I can wait for the callback function to resolve before proceeding?

    – J W
    Nov 25 '18 at 21:33

















the wording always doesn't suit with async.

– Bhojendra Rauniyar
Nov 25 '18 at 21:23





the wording always doesn't suit with async.

– Bhojendra Rauniyar
Nov 25 '18 at 21:23













Thank you for answering. That does seem to be the issue. Is there any way I can wait for the callback function to resolve before proceeding?

– J W
Nov 25 '18 at 21:33





Thank you for answering. That does seem to be the issue. Is there any way I can wait for the callback function to resolve before proceeding?

– J W
Nov 25 '18 at 21:33











1














getDownloadURL().then(...) looks like an asynchronous function to me. Asynchronous (async for short) means that the javascript makes an external request (e.g. download a file) and then executes a callback function (the argument to then) once the external request is complete. In general you should expect javascript async callbacks to execute after the entire function call stack that starts the request.



Most programming languages with asynchronous functions will have a facility to wait, which is often called "blocking", but Javascript is an exception.



The reason Javascript does not permit blocking is Javascript engines are single threaded, so blocking on an operation blocks the whole system.



So for a long time, couldn't block a function to wait for the async calls to finish and pick up as if they were ordinary synchronous calls.



This is so inconvenient, Javascript eventually introduced async functions and the await keyword, which does what you want.



async function buildHtml(snapshot) {
// Note the novel for-loop syntax. The inner function in forEach would break async.
for(childSnapshot of snapshot) {
var childKey = childSnapshot.key;
var childData = childSnapshot.val();
myHTML += '<div class="card">';
myHTML += '<div class="card-body">';
var urlimage = await storageRef.child('images/'+ childData.id +'.jpg').getDownloadURL(); // global state may change here
myHTML += '<img src="'+ urlimage +'" class="img-thumbnail" height="">';
myHTML += '<h4>'+ childData.sku + ' - ' + childData.name +'</h4>';
myHTML += '</div>';
myHTML += '</div>';
}
wrapper.innerHTML = myHTML;
}





share|improve this answer


























  • Thank you for answering. That does seem to be the issue. Is there any way I can wait for the callback function to resolve before proceeding?

    – J W
    Nov 25 '18 at 21:33











  • @JW yes, await. It's new, surprisingly.

    – 01d55
    Nov 28 '18 at 4:58
















1














getDownloadURL().then(...) looks like an asynchronous function to me. Asynchronous (async for short) means that the javascript makes an external request (e.g. download a file) and then executes a callback function (the argument to then) once the external request is complete. In general you should expect javascript async callbacks to execute after the entire function call stack that starts the request.



Most programming languages with asynchronous functions will have a facility to wait, which is often called "blocking", but Javascript is an exception.



The reason Javascript does not permit blocking is Javascript engines are single threaded, so blocking on an operation blocks the whole system.



So for a long time, couldn't block a function to wait for the async calls to finish and pick up as if they were ordinary synchronous calls.



This is so inconvenient, Javascript eventually introduced async functions and the await keyword, which does what you want.



async function buildHtml(snapshot) {
// Note the novel for-loop syntax. The inner function in forEach would break async.
for(childSnapshot of snapshot) {
var childKey = childSnapshot.key;
var childData = childSnapshot.val();
myHTML += '<div class="card">';
myHTML += '<div class="card-body">';
var urlimage = await storageRef.child('images/'+ childData.id +'.jpg').getDownloadURL(); // global state may change here
myHTML += '<img src="'+ urlimage +'" class="img-thumbnail" height="">';
myHTML += '<h4>'+ childData.sku + ' - ' + childData.name +'</h4>';
myHTML += '</div>';
myHTML += '</div>';
}
wrapper.innerHTML = myHTML;
}





share|improve this answer


























  • Thank you for answering. That does seem to be the issue. Is there any way I can wait for the callback function to resolve before proceeding?

    – J W
    Nov 25 '18 at 21:33











  • @JW yes, await. It's new, surprisingly.

    – 01d55
    Nov 28 '18 at 4:58














1












1








1







getDownloadURL().then(...) looks like an asynchronous function to me. Asynchronous (async for short) means that the javascript makes an external request (e.g. download a file) and then executes a callback function (the argument to then) once the external request is complete. In general you should expect javascript async callbacks to execute after the entire function call stack that starts the request.



Most programming languages with asynchronous functions will have a facility to wait, which is often called "blocking", but Javascript is an exception.



The reason Javascript does not permit blocking is Javascript engines are single threaded, so blocking on an operation blocks the whole system.



So for a long time, couldn't block a function to wait for the async calls to finish and pick up as if they were ordinary synchronous calls.



This is so inconvenient, Javascript eventually introduced async functions and the await keyword, which does what you want.



async function buildHtml(snapshot) {
// Note the novel for-loop syntax. The inner function in forEach would break async.
for(childSnapshot of snapshot) {
var childKey = childSnapshot.key;
var childData = childSnapshot.val();
myHTML += '<div class="card">';
myHTML += '<div class="card-body">';
var urlimage = await storageRef.child('images/'+ childData.id +'.jpg').getDownloadURL(); // global state may change here
myHTML += '<img src="'+ urlimage +'" class="img-thumbnail" height="">';
myHTML += '<h4>'+ childData.sku + ' - ' + childData.name +'</h4>';
myHTML += '</div>';
myHTML += '</div>';
}
wrapper.innerHTML = myHTML;
}





share|improve this answer















getDownloadURL().then(...) looks like an asynchronous function to me. Asynchronous (async for short) means that the javascript makes an external request (e.g. download a file) and then executes a callback function (the argument to then) once the external request is complete. In general you should expect javascript async callbacks to execute after the entire function call stack that starts the request.



Most programming languages with asynchronous functions will have a facility to wait, which is often called "blocking", but Javascript is an exception.



The reason Javascript does not permit blocking is Javascript engines are single threaded, so blocking on an operation blocks the whole system.



So for a long time, couldn't block a function to wait for the async calls to finish and pick up as if they were ordinary synchronous calls.



This is so inconvenient, Javascript eventually introduced async functions and the await keyword, which does what you want.



async function buildHtml(snapshot) {
// Note the novel for-loop syntax. The inner function in forEach would break async.
for(childSnapshot of snapshot) {
var childKey = childSnapshot.key;
var childData = childSnapshot.val();
myHTML += '<div class="card">';
myHTML += '<div class="card-body">';
var urlimage = await storageRef.child('images/'+ childData.id +'.jpg').getDownloadURL(); // global state may change here
myHTML += '<img src="'+ urlimage +'" class="img-thumbnail" height="">';
myHTML += '<h4>'+ childData.sku + ' - ' + childData.name +'</h4>';
myHTML += '</div>';
myHTML += '</div>';
}
wrapper.innerHTML = myHTML;
}






share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 28 '18 at 4:49

























answered Nov 25 '18 at 21:22









01d5501d55

1,6041119




1,6041119













  • Thank you for answering. That does seem to be the issue. Is there any way I can wait for the callback function to resolve before proceeding?

    – J W
    Nov 25 '18 at 21:33











  • @JW yes, await. It's new, surprisingly.

    – 01d55
    Nov 28 '18 at 4:58



















  • Thank you for answering. That does seem to be the issue. Is there any way I can wait for the callback function to resolve before proceeding?

    – J W
    Nov 25 '18 at 21:33











  • @JW yes, await. It's new, surprisingly.

    – 01d55
    Nov 28 '18 at 4:58

















Thank you for answering. That does seem to be the issue. Is there any way I can wait for the callback function to resolve before proceeding?

– J W
Nov 25 '18 at 21:33





Thank you for answering. That does seem to be the issue. Is there any way I can wait for the callback function to resolve before proceeding?

– J W
Nov 25 '18 at 21:33













@JW yes, await. It's new, surprisingly.

– 01d55
Nov 28 '18 at 4:58





@JW yes, await. It's new, surprisingly.

– 01d55
Nov 28 '18 at 4:58


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53472038%2fjavascript-code-executing-out-of-order-can-i-fix-it%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks

Calculate evaluation metrics using cross_val_predict sklearn

Insert data from modal to MySQL (multiple modal on website)