Skip to content

only pass a reference to the function #5

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 20, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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);
  • Loading branch information
@leonardofed authored Dec 18, 2018
commit 96d7846b892c2e4ec37040c494b4ac21fa65b4e6
Original file line number Diff line number Diff line change
Expand Up @@ -150,10 +150,12 @@ console.log('End of Challenge 5');
//CHALLENGE 6//
console.log('Start of Challenge 6');
var dataReceived;
var data; // is undefined at first

function ajaxSimulate(id, callback) {
var database = ['Aaron', 'Barbara', 'Chris'];
setTimeout(callback(database[id]), 0);
var data = database[id]
setTimeout(callback, 0);
}

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

console.log('End of Challenge 9');
console.log('End of Challenge 9');