Skip to content

Commit 96d7846

Browse files
author
@leonardofed
authored
only pass a reference to the function
this is conceptually wrong since the SetTimeout is going to exectue the callback immediately and the function never gets passed in the callback queue. solution, leverage closure and set the database[id] in a global variable. var dataReceived; var data; // is undefined at first function ajaxSimulate(id, callback) { var database = ['Aaron', 'Barbara', 'Chris']; data = database[id] setTimeout(callback, 0); } function storeData() { dataReceived = data; console.log(dataReceived); } ajaxSimulate(1, storeData);
1 parent 0286522 commit 96d7846

File tree

1 file changed

+4
-2
lines changed

1 file changed

+4
-2
lines changed

2018-01-22-javascript-hard-parts/fem-JavaScriptTheHardParts-AsynchronicitySolutions.js

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -150,10 +150,12 @@ console.log('End of Challenge 5');
150150
//CHALLENGE 6//
151151
console.log('Start of Challenge 6');
152152
var dataReceived;
153+
var data; // is undefined at first
153154

154155
function ajaxSimulate(id, callback) {
155156
var database = ['Aaron', 'Barbara', 'Chris'];
156-
setTimeout(callback(database[id]), 0);
157+
var data = database[id]
158+
setTimeout(callback, 0);
157159
}
158160

159161
function storeData(data) {
@@ -242,4 +244,4 @@ function dataHandler(data) {
242244
$("#ch4").slice(0, -1); //takes off the extra comma
243245
}
244246

245-
console.log('End of Challenge 9');
247+
console.log('End of Challenge 9');

0 commit comments

Comments
 (0)