Last active
December 28, 2015 01:09
-
-
Save pavelpower/7418193 to your computer and use it in GitHub Desktop.
Вообще откуда ноги у callback. Посмотри этот пример
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var data = [ | |
{ | |
id: 23, | |
name: 'Sasha', | |
age: 43 | |
}, | |
{ | |
id: 65, | |
name: 'Pasha', | |
age: 12 | |
}, | |
{ | |
id: 234, | |
name: 'Nasha', | |
age: 43 | |
}, | |
{ | |
id: 123, | |
name: 'Alex', | |
age: 12 | |
} | |
]; | |
function find(id, callback) { | |
// представим, что у нас работает устройство = жесткий диск | |
// и стобы получить с него данные на каждую итерацию | |
// надо время не мениее 1 секунды | |
setTimeout(function() { | |
// а тут мы получили данные | |
// и можем делатать поиск | |
var count = data.length, | |
i = 0, | |
is_find = false; | |
while (i < count && is_find === false) { | |
// некий цикл ожилдагия получени данных | |
is_find = data[i].id === id; | |
if (is_find) { | |
callback.call(data, data[i], i); | |
} | |
i++; | |
} | |
}, 1000); | |
} | |
find(234, function(user, position) { | |
console.log(' length:', this.length); | |
console.log('find data: ', user.name, user.age, ' in position:', position); | |
}); | |
// этот код выполнится быстрее чем поиск | |
// несмотря на то, что он идет сразу после поиска | |
console.log('этот код выполнится быстрее чем поиск', 2 + 2); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment