My client-side JS app requires loading a template to display each item, such as notes.
The issue lies in the asynchronous aspect. The template loads every time a note calls the render
function instead of just once.
Below is some code snippet:
var notes = [ {}, {}, {} ] // Some Note objects
notes.forEach( function( note ) {
render( note )
}
// Variable to store the template
var template
// Render function
function render( note ) {
// Check if the template exists and proceed
if ( template ) {
display( note )
}
else {
loadTemplate( function( data ) {
template = data
display( note )
} )
}
}
Despite having a check to prevent multiple template loads, in this scenario, it loads the templates three times consecutively due to all going into the else statement. How can I avoid this?
I want to avoid using synchronous ajax as it could freeze the browser.
Edit: To address the issue, I implemented @Managu's solution with slight modifications.
Instead of his loop, I opted for a more elegant approach:
while ( backlog.length ) {
display( backlog.shift() )
}