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

Conversation

leonardofed
Copy link

@leonardofed leonardofed commented Dec 18, 2018

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; 

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);

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);
@1Marc 1Marc merged commit e1b4b77 into FrontendMasters:master Dec 20, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants