나는 아래에 표기하기 다음해서 getJSON가 발생 될 때까지
$.getJSON(
twitter_api_url + '?callback=?&rpp=100&q=text::)',
function(data) {
$.each(data.results, function(i, tweet) {
//console.log(tweet);
// Before we continue we check that we got data
if(tweet.text !== undefined) {
//here we save the time of our happy tweet
var date_tweet = new Date(tweet.created_at);
per_sec[i] = date_tweet/1000;
//console.log(per_sec[i]);
}
});
//here we calculate how manny happy tweets the world tweets per second
smile_per_sec = 100/(per_sec[0]-per_sec[98])
$('#tweet_container').append(smile_per_sec + "<br>");
///////////////////////////////////////////////
// this is place one
///////////////////////////////////////////////
console.log(smile_per_sec);
return smile_per_sec;
}
);
///////////////////////////////////////////////
// this is place two
///////////////////////////////////////////////
console.log(smile_per_sec);
장소 두 실행하는 즉시, 하나 개의 대기를 놓습니다. 이를 비동기 프로그래밍이라고합니다. 얻을 때까지 값을 사용할 수 없으며, "다른 것이 끝내기를 기다리는"것을 원하는 경우 flexibile 비동기 프로그래밍 기술을 채택해야합니다.
사람들이 자바 스크립트에서 이벤트 또는 콜백에 대해 이야기 할 때마다, 그들이 말하는 내용입니다. 이 경우 콜백은 세 번째 줄에 function(data)
으로 시작됩니다.
내가 자세히 설명 할 필요가 있다고 생각, 내가 그렇게하자
$.getJSON(...);
console.log(smile_per_sec);
이 두 효과적으로 "같은 시간"에서 운영하고 있습니다. getJSON에서 일어나는 일은 완료 될 때까지 백 버너에 머물러있어 페이지가 계속 물건을 처리하게합니다. 그래서 console.log가 앞으로 나아가서 튀어 나오지 만, 후방 버너가 정면으로 돌아 오지 않았기 때문에, 물은 아직 비등하지 않습니다. 그래서 물이 끓을 때까지 (10ms가 될 수 있습니다, 3 분이 될 수 있습니다) 물이나 물속에있는 국수 등으로 무엇이든 할 수 없습니다.
처음에는 이것을 이해하기가 까다 롭지 만 일단 이것을 얻으면이 아약스 전체가 나옵니다.
은의 질문에 대답에 대한 대답은 다음과 같이 코드를 구조 조정하는 것입니다 "어떻게이 완료되면이 모든 일을해야합니까"당신이 달성하려고하는 무엇
// Here we've made this a named function, and allowed the function to be more neatly encapsulated
function twitterCallback(data) {
$.each(data.results, function(i, tweet) {
//console.log(tweet);
// Before we continue we check that we got data
if(tweet.text !== undefined) {
//here we save the time of our happy tweet
var date_tweet = new Date(tweet.created_at);
per_sec[i] = date_tweet/1000;
//console.log(per_sec[i]);
}
});
//here we calculate how manny happy tweets the world tweets per second
smile_per_sec = 100/(per_sec[0]-per_sec[98])
$('#tweet_container').append(smile_per_sec + "<br>");
console.log(smile_per_sec);
return smile_per_sec;
///////////////////////////////////////////////
// this is where you put stuff that has to wait on twitter to return
///////////////////////////////////////////////
}
$.getJSON(
twitter_api_url + '?callback=?&rpp=100&q=text::)',
twitterCallback
);
를? – jcolebrand
** ** - 동기. –