I have a 함수은 Ajax 요청을 하는 'foo' 만듭니다. 반응이 반품하십시오 foo '' 어떻게 해야 합니까?
전화했는데 반환 '성공' 뿐만 아니라 지역 지정 가치를 콜백하는 응답 변수 함수 내에 있지만 아무도 그 뒤 실제로 이러한 방법으로 반품해야 반응을 보였다.
function foo() {
var result;
$.ajax({
url: '...',
success: function(response) {
result = response;
// return response; // <- I tried that one as well
}
});
return result;
}
var result = foo(); // It always ends up being `undefined`.
>. & 라르;; 더 일반적인 예는 비동기 행동에 대한 설명, 서로 다른 참조하시기 바랍니다 https://stackoverflow.com/q/23667086/218196 >. >. & 라르;; 이미 문제의 이해 가능한 솔루션을 below. 건너뛰십시오 경우,
그에게 전화를 걸어 친구는요 상상할 수 있게 하며 여바바 뭔가 백업하도록 당신꺼에요. 다소 시간이 걸릴 수 있지만, 기다리게 표기돼 있는 친구에게 전화를 걸어 당신이 필요로 하는 때까지 우주로 대답할 수 있습니다. 같은 문제가 발생하였는가 만들 때, 함수 호출 " redboot*용 normal". 코드:
function findItem() {
var item;
while(item_not_found) {
// search
}
return item;
}
var item = findItem();
// Do something with item
doSomethingElse();
비록 ',' 모든 코드를 실행하는 데 시간이 오래 걸릴 수 있으며 핀디템 '후' 가 나올 때까지 기다려 , = var 품목으로부터 핀디템 () 함수는 그 결과.
다시 전화하시기 친구 같은 이유로. 하지만 이 때 그는 다시 전화 할께 아, 이거 녹음되는거지 중인 휴대폰 화면에 있는 한다. 너희가 원하는 대로 할 수 있는 집과 남겨두십시오 너회가 끊어, 친구, 너를 다시 한번 계획된 페이징됩니다 틀렸다니까 준 정보를 다룰 수 있습니다.
findItem(function(item) {
// Do something with item
});
doSomethingElse();
! 동시에 아우르는 특성상 특정 제품과 비동기식 (asynchronous JavaScript (so 가 Ajax" ";), 동기식 운영체 제공하십시오 it& # 39 의 은폐하고 이를 이용하는 것이 일반적으로, 특히 있지만브라우저에 컨텍스트입니다. 많이 다치셨대요 왜 그러세요? JavaScript UI 에서 실행 중인 프로세스를 실행할 수 있기 때문에 모든 기절해있는 브라우저의 스레드할 잠급니다 ᅴ 응답하지 않는. 또한 JavaScript 를 실행 시간 제한이 쇱そ 백업이었습니다 및 브라우저는 사용자가 계속 엑서큐션 방관하겠나 분할할지를 요구할 예정이다. 이 모든 것이 정말 나쁜 사용할 수 있습니다. # 39, 모든 것을 말할 수 있을 수 없는 사용자가 won& 표시할지를 정상적으로 작동하는 방관하겠나 효과가 있는 사용자를 위해 느린 연결 더욱 악화될 전망이다. 그 다음 3 가지 솔루션을 기반으로 모두 서로 알아보도록 하겠습니다.
Ecma 스크립트 버전) 는 2017년 발매된 이 대한 지원 구문 수준 비동기적입니다 총괄하였습니다. 도움을 기다리는 ',' 와 '' 비동기 비동기 받을시간은 ", 동기식 style", 쓸 수 있습니다. 이 코드는 쉽게 읽을 수 있지만, 여전히 비동기적입니다 it& # 39, s / understand. '약속' 비동기 / 기다리는 토대로. '한' 비동기 함수 항상 약속이 되돌려줍니다. ',' " 기다리는 unwraps". 한 약속과 함께 또는 오류가 발생할 경우 이 값은 인컨텍스트 약속하나요 해결되었습니다 던지는 약속하나요 거절당했다.
// Using 'superagent' which will return a promise.
var superagent = require('superagent')
// This is isn't declared as `async` because it already returns a promise
function delay() {
// `delay` returns a promise
return new Promise(function(resolve, reject) {
// Only `delay` is able to resolve or reject the promise
setTimeout(function() {
resolve(42); // After 3 seconds, resolve the promise with value 42
}, 3000);
});
}
async function getAllBooks() {
try {
// GET a list of book IDs of the current user
var bookIDs = await superagent.get('/user/books');
// wait for 3 seconds (just for the sake of this example)
await delay();
// GET information about each book
return await superagent.get('/books/ids='+JSON.stringify(bookIDs));
} catch(error) {
// If any of the awaited promises was rejected, this catch block
// would catch the rejection reason
return null;
}
}
// Start an IIFE to use `await` at the top level
(async function(){
let books = await getAllBooks();
console.log(books);
})();
단지 다른 함수에 전달된 콜백 함수. 그 때마다 통과한 다음 함수 호출 기능은 준비되었음. 컨텍스트에서 비동기적입니다 프로세스를 될 때마다 불렀으매 콜백하는 비동기적입니다 프로세스를 완료했습니다. 일반적으로, 그 결과 콜백하는 전달됩니다. 예를 들어, '는 질문에' 성공 '으로 콜백하는 및 사용 할 수 있습니다' foo 동의하십시오 콜백하는. 이 때문에
var result = foo();
// Code that depends on 'result'
됩니다
foo(function(result) {
// Code that depends on 'result'
});
여기서 함수 정의된 " inline"; 하지만 모든 함수 참조입니다 전달할 수 있습니다.
function myCallback(result) {
// Code that depends on 'result'
}
foo(myCallback);
foo '자체가' 는 다음과 같이 정의된다.
function foo(callback) {
$.ajax({
// ...
success: callback
});
}
'우리' 가 '때' () 는 다음과 같은 함수 콜백하는 패스를 우리들은 이를 단순히 '성공' 에 foo 하나님은 통과시킬. E. i. 일단 Ajax 호출 ',' 성공 '과' 가 $ 지아이아스 요청인지 콜백하는 대한 응답을 전달하십시오 콜백하는 (될 수 있는 '을 (를)' 라고 정의하고, 그 이후 this is how we 콜백하는). 그 전에 응답을 반군지역 콜백하는 처리할 수도 있습니다.
function foo(callback) {
$.ajax({
// ...
success: function(response) {
// For example, filter the response
callback(filtered_response);
}
});
}
이 약속하나요 apiu 는 새로운 기능이 있지만 아직 优秀 ECMAScript 6 (ES2015) [브라우저 지원] [10] 이미. 또한 많은 공약을 어떤 방법으로도 표준 라이브러리 API 를 사용 및 컴포지션에 구현하십시오 제공하십시오 부드럽게를 비동기 함수 (예: 블루버드).
function delay() {
// `delay` returns a promise
return new Promise(function(resolve, reject) {
// Only `delay` is able to resolve or reject the promise
setTimeout(function() {
resolve(42); // After 3 seconds, resolve the promise with value 42
}, 3000);
});
}
delay()
.then(function(v) { // `delay` returns a promise
console.log(v); // Log the value once it is resolved
})
.catch(function(v) {
// Or do something else if it is rejected
// (it would not happen in this example, since `reject` is not called).
});
우리는 우리의 Ajax 호출 발려짐 사용할 수 있는 것은 다음과 같습니다.
function ajax(url) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
resolve(this.responseText);
};
xhr.onerror = reject;
xhr.open('GET', url);
xhr.send();
});
}
ajax("/echo/json")
.then(function(result) {
// Code depending on result
})
.catch(function() {
// An error occurred
});
이 모든 것을 설명하는 장이점이 약속하나요 오퍼링에 범위를 넘어서는 새로운 코드를 작성하는 농담하십니까 저들이요 고려해보십시오 신앙이니라 대답을 합니다. 그들은 숭배자들로부터도 추상화 및 분판 제공하십시오 코드에 있다. 자세한 내용은 그렇다. [HTML5 바위 - JavaScript 약속] [12]
우회된 객체에는 가 jQuery& # 39 의 사용자 정의 구현 약속 (Promise 전에 API 는 표준화했습니다). 하지만 약간 다른 apiu 거의 같은 주요 공약 동작합니다. Jquery 는 이미 모든 방법을 되돌려줍니다 ", 아약스는 우회된 object". (실제로는 한 약속이 우회된 객체에는) 에서 그냥 반품하십시오 수 있는 기능:
function ajax() {
return $.ajax(...);
}
ajax().done(function(result) {
// Code depending on result
}).fail(function() {
// An error occurred
});
function checkPassword() {
return $.ajax({
url: '/password',
data: {
username: $('#username').val(),
password: $('#password').val()
},
type: 'POST',
dataType: 'json'
});
}
if (checkPassword()) {
// Tell the user they're logged in
}
이 코드는 오해 위의 비동기 문제. 특히 doesn& 지아이아스 () ',' $ # 39, & # 39 /password& # 39 동안 코드를 t 동결합니다 검사합니다. 페이지 요청을 보냅니다 서버에서 동시에 즉시 이 아닌 한, 서버 및 Ajax 서버의 응답을 우회된 객체에는 되돌려줍니다 포함한다. 즉, "만약 '기술서임을 진행 과정은 항상 afaq afnor 우회된 객체에는, 치료, 이를' true '로 진행하십시오 것처럼 사용자가 로그인되었습니다. 안 좋아요. 그러나 수리입니다 쉽지 않다.
checkPassword()
.done(function(r) {
if (r) {
// Tell the user they're logged in
} else {
// Tell the user their password was bad
}
})
.fail(function(x) {
// Tell the user something bad happened
});
앞서 언급했듯이, 일부 (!) 비동기적입니다 작업에서는 동기식 도착했습니다. 그렇지만 내가 don& # 39, t 정보지지자 사용법을 completeness& # 39. 제발 슬라이드에서는 동기식 호출하십시오 어떻게 수행할 것입니다.
'스믈하트프리퀘스트' 객체에는 직접 사용하는 경우 '거짓' 으로 전달하십시오 3 인수를 ['자오픈'] [15].
JQuery 사용하는 경우 '거짓', '비동기' 옵션을 설정할 수 있습니다. 참고로 이 옵션은 이후 사용되지 않는 유일한 1.8pb 포함한다. '성공' 한 계속 사용할 수 있습니다 다음 콜백하는 액세스하려면 레스폰스테스트 [이크스어 객체에는] [17] '또는' 속성 중 하나이다.
function foo() {
var jqXHR = $.ajax({
//...
async: false
});
return jqXHR.responseText;
}
Jquery '$ 이제 아약스 등 다른 방법을 사용하는 경우', '' 등 합니다 '$ $ 이제이슨 변경하십시오 지아이아스' (이후 '$ 지아이아스 전달하십시오 구성 매개 변수를 사용할 수 있습니다').
뭔가 이 코드에 따라 흐름선 합니다.
function foo() {
var httpRequest = new XMLHttpRequest();
httpRequest.open('GET', "/echo/json");
httpRequest.send();
return httpRequest.responseText;
}
var result = foo(); // always ends up being 'undefined'
Jquery 를 사용한 사람들은 그에 대한 답을 AJAX 작업을 한 펠릭스 클링 벌금을 먹어서나 I& # 39, ve 대체 백성을위한 aren& # 39, t 지원키로 했다.
([참고) 를 사용하는 새로운 '페치할' 공약 I& # 39, ve, 각 API 또는 다른 답을 추가되든지 아래] (https://stackoverflow.com/a/30180679/1348195))
간단한 요약, 이는 " problem" 대한 설명. # 39 에서 다른 대답을 잘 모를 경우 you& 읽은 후, 읽기, re iqn.
A 비동기적입니다 있는 AJAX 를 의미합니다. 즉, 보내는 요청 (또는 대답하도다 받은 응답) 을 빼내 정상 실행 흐름. ['이젠드'] [1] 에 들어, 다음, 그 결과, ',' 는 즉시 되돌려줍니다 기술서임을 복귀하십시오 '성공' 로 불리는 그는 전에 오빠, 통과했을거에요 함수은 csetup 콜백하는.
즉, 이 때, # 39, ve you& you& # 39, re 다시 리스너에 정의된 값, 즉, 아직 실행되지 않았다 you& # 39 는 re 다시 정의되지 않았다.
다음은 간단한 비유
function getFive(){
var a;
setTimeout(function(){
a=5;
},10);
return a;
}
[(바이올린)] [2]
'A' 는 '이후' 의 값이 정의되지 않은 '5' 가 a = 반환되었습니다 부품 실행되지 못했다. # 39, 아약스는 이 같은 행위를 하고 you& 전에 값을 반환하는 값은 브라우저를 떠날려하면 서버만을 할 수 있는 기회를 얻었다.
이 문제에 대한 해결 방안을 알려줄 수 있는 한 것이 어떻게 해야 할 때, 좋아하는 프로그램 코드 re-actively 계산 완료.
function onComplete(a){ // When the code completes, do this
alert(a);
}
function getFive(whenDone){
var a;
setTimeout(function(){
a=5;
whenDone(a);
},10);
}
이 호출됨 CPS. 기본적으로 we& # 39, re 반군지역 '액션' 때, # 39, re telling 제프리베 진행하십시오 완료하는지 we& lionbridge 코드를 어떻게 대응해야 이벤트로 완료하는지 (우리와 우리의 AJAX 호출 또는 이 경우, 시간 초과).
사용 될 수 있다.
getFive(onComplete);
하는 경고마다 " 5"; 화면에. [(바이올린)] [4].
기본적으로 두 가지 방법을 방법으로 이 문제를 해결할 수 있습니다.
>. 스믈하트프리퀘스트 모두 지원 동기 / 비동기) 이었다. 그러나 일반적으로 비동기적입니다 요청률 성능 상의 이유로 우선 생성에서부터 동기식 요청률 합니다.
>. 한마디로 동기식 요청률 코드 실행 차단. 스티스 심각한 문제를 일으킬 수 있다.
플래그 have 경우 이를 전달할 수 있습니다. [5] [Here is how:]
16 438 {{{000}}}
Let your 함수은 콜백하는 받아들인다. 예를 들어, '코드' foo 콜백하는 허용할 수 있도록 만들 수 있습니다. # 39, foo 'll be telling react 방법을 통해 코드 we& 때' 완료하는지.
그래서:
var result = foo();
// code that depends on `result` goes here
됩니다.
foo(function(result) {
// code that depends on `result`
});
하지만 여기서 우리는 우리가 할 수 있었던 것처럼 참조입니다 익명의 함수를 쉽게 전달할 수 있기 때문에 기존 함수를 다음과 같습니다.
function myHandler(result) {
// code that depends on `result`
}
foo(myHandler);
이러한 종류의 콜백하는 설계 방법에 대한 자세한 내용은 # 39 의 확인란 Felix& 완료되어도, 그 답이 있다.
지금 # 39, 그에 따라 행동할 수 자체가 정의하십시오 let& s foo
function foo(callback) {
var httpRequest = new XMLHttpRequest();
httpRequest.onload = function(){ // when the request is loaded
callback(httpRequest.responseText);// we're calling our method
};
httpRequest.open('GET', "/echo/json");
httpRequest.send();
}
[(바이올린)] [6]
이제 한 때, 우리는 우리의 foo 함수은 액션을 동의하십시오 실행하십시오 AJAX 성공적으로 완료되면 이 추가 확장할 수 없는 200mb/s 그에 따라, 연기 여부를 확인하여 응답 상태 (페일오버합니다 처리기에서 만들기 등). 우리의 문제를 효과적으로 해결하기 위해.
[1]: # send% 28%29 https://developer.mozilla.org/en-us/docs/web/api/xmlhttprequest
[5]: # Synchronous_request https://developer.mozilla.org/en-us/docs/web/api/xmlhttprequest/synchronous_and_asynchronous_requests
function ajax(a, b, c){ // URL, callback, just a placeholder
c = new XMLHttpRequest;
c.open('GET', a);
c.onload = b;
c.send()
}
알 수 있듯이.
this.response
You ' ()' 의 경우 또는 몇 가지 이유로 바인딩해야 콜백하는 맞추기바인딩 클래스:
e.target.response
예:
function callback(e){
console.log(this.response);
}
ajax('URL', callback);
또는 (위의 익명 함수 게 더 좋은데 항상 문제가):
ajax('URL', function(e){console.log(this.response)});
아무것도아니야 간편해집니다. 일부 사람들은 지금 말하는 것으로, 또는 심지어 스믈하트프리퀘스트 를 사용할 수 있는 더 나은 모리디국가창레 it& # 39 의 변수 이름. # 39 의 that& 잘못된. 체크아웃하려고 스믈하트프리퀘스트 고급 기능을
function x(a, b, e, d, c){ // URL, callback, method, formdata or {key:val},placeholder
c = new XMLHttpRequest;
c.open(e||'get', a);
c.onload = b;
c.send(d||null)
}
다시. # 39 의 it& 않지만, 매우 짧은 함수은 프레젠테이션이든 &. 포스트. 용례:
x(url, callback); // By default it's get so no need to set
x(url, callback, 'post', {'key': 'val'}); // No need to set post data
전체 양식 또는 성공 요소 ('도쿠망스게테레멘츠비타냐메 (& # 39, form& # 39;) [0]').
var fd = new FormData(form);
x(url, callback, 'post', fd);
일부 사용자 정의 또는 설정 값:
var fd = new FormData();
fd.append('key', 'val')
x(url, callback, 'post', fd);
논평에서 언급한 바와 같이 사용하는 오류 & &; 동기식 높여줍니까 완전히 끊을 집중식으로 해답이야 이는 좋은 파선-짧은 아약스 적절한 방식으로 사용 방법은?
function x(a, b, e, d, c){ // URL, callback, method, formdata or {key:val}, placeholder
c = new XMLHttpRequest;
c.open(e||'get', a);
c.onload = b;
c.onerror = error;
c.send(d||null)
}
function error(e){
console.log('--Error--', this.type);
console.log('this: ', this);
console.log('Event: ', e)
}
function displayAjax(e){
console.log(e, this);
}
x('WRONGURL', displayAjax);
위의 경우 스크립트입니다 처리기에서 정의된 함수가 오류 때문에 정적으로 원하는거요 영향을 미치지 않습니다. 오류 처리기에서 너무 다른 기능을 사용할 수 있습니다. 하지만 이 방법은 정말 쓰기 전용 나가버렷 오류가 있는 경우 잘못된 uirl 모든 브라우저 던지는 오류가 발생했습니다. 아마 설정할 경우, 사용자 정의 오류 처리기 헤더도 레스폰세이페 설정할 수 있는 유용한 물방울 어레이입니다 버퍼 또는 그러든지요
첫 번째 케이스의 오류: 내부의 디스플레아이아스 () '으로' 방법 '' 아래 '티스리스테우스테스트 미허용'. 두 번째 경우 이는 단순히 작동합니다. 오빠, 통과했을거에요 때는기대어 서버의 경우 오른쪽 골대를 데이터를 확인할 수 있습니다. 크로스-도메인 미허용 오류가 자동으로 던진다. 오류 응답을 오류 코드 없습니다. 이 밖에 '는' 티스스티페 설정되었습니다 오류:. 왜 오류가 처리기에서 완전히 제어할 수 없는 경우 추가 오류뿐만? 이 중 대부분의 오류는 반환되었습니다 인사이드라면 디스플레아이아스 콜백 함수를 ' ()'. 그래서: # 39 you& 오류 확인 필요 없는 경우, 복사 및 붙여넣습니다 uirl 제대로 할 수 있을 정도다. )
function omg(a, c){ // URL
c = new XMLHttpRequest;
c.open('GET', a, true);
c.send();
return c; // Or c.response
}
이제 할 수 있습니다.
var res = omg('thisIsGonnaBlockThePage.txt');
위의 기본 기능을 사용할 수 있다. 스케쳐내 확장할 수 있다. 그래, 넌 할 수 있습니다.
하지만 당신은 할 수 있는 많은 물건을 스믈하트프리퀘스트 2: I made a 다운로드 매니저 (범위, 양측 모두 사용하여 다시 시작하는 필레이더, 파일 시스템), 다양한 이미지 컨버터 등을 통해 정보를 사용하여 SQL 데이터베이스, 웹 레지저스 캔바스를 base64images. 그러나 이 경우 이를 위해 기능만 만들어야 합니다. 가끔 위치한, 어레이입니다 버퍼를 필요로 하는 많은 이유가 있고, mime 형식 오버라이드합니다 헤더도 설정할 수 있습니다. 하지만 아약스는 다시 볼 수 있는 대응 방법은 다음과 같습니다. (내가 쉽게 추가되든지.)
즉, jQuery 를 우회된), 네이티브 XHR& 앙굴라이스 # 39 의 교체품을 엠베리스 BackboneJS& # 39 의 모든 노드 라이브러리 (페치할), 저장 또는 반환하는 공약. 뭔가 이 코드에 따라 흐름선 합니다.
function foo() {
var data;
// or $.get(...).then, or request(...).then, or query(...).then
fetch("/echo/json").then(function(response){
data = response.json();
});
return data;
}
var result = foo(); // result is always undefined no matter what.
Javascript 가 브라우저에서 동시성 모델 및 서버의 NodeJS/io.js 함께 asynchronous 및 reactive. 이 후 반환하는 약속하나요 메서드입니다 전화하시기 때마다 '즉, 그 아래 코드는 after 비동기적으로 실행됨을 핸들러도 always 있다' 는 '아닌' .즉 처리기에서. 즉, '다음' 의 '돌아온 you& 때, re # 39 의 데이터 정의 you& 처리기에서 # 39, ve 아직 실행되지 않았다. 즉, re 반환 값은 # 39 이 선반가공 you& 올바른 가치를 시간이 아직 정해지지 않았다. 다음은 이 문제를 해결하기 위해 간단한 비유: <! - begin 스니핏: js 숨기십시오: > 거짓값 -;
function getFive(){
var data;
setTimeout(function(){ // set a timer for one second in the future
data = 5; // after a second, do this
}, 1000);
return data;
}
document.body.innerHTML = getFive(); // `undefined` here and not 5
끝 - < 스니핏 >;! 이후 '는' 의 데이터 값이 정의되지 않은 '5' 는 '데이터 = 부품 실행되지 못했다. 실행할 수 있는 시간을 고려하면 공산이 크다 두 번째 값을 반환되었습니다 중요하지 않습니다. 이후 작업이 아직 일어나지 않았다 (i / o, 아약스, 서버, 인터넷 전화 타이머), re 전에 값을 반환하는 요청 attaboy you& # 39 할 기회가 tell your 코드 값은. 이 문제에 대한 해결 방안을 알려줄 수 있는 한 것이 어떻게 해야 할 때, 좋아하는 프로그램 코드 re-actively 계산 완료. 이 시간 (시간에 민감한) 에 의해 적극적으로 활성화하십시오 기술입니까 약속을 이행하지 않았다.
약속 (promise 는 통해 value time. 약속을 잡을 수 있고, 그 가치가 없는 보류 상태로 시작 할 수 있다.
function delay(ms){ // takes amount of milliseconds
// returns a new promise
return new Promise(function(resolve, reject){
setTimeout(function(){ // when the time is up
resolve(); // change the promise to the fulfilled state
}, ms);
});
}
우리는 이제 뒤에을 [변환되었습니다 setTimeout] (stackoverflow.com/questions/22519784/how-do-i-convert-an-existing-callback-api-to-promises), '약속' 을 사용할 수 있습니다 다음 잘쏴: <! - begin 스니핏: js 숨기십시오: > 거짓값 -;
function delay(ms){ // takes amount of milliseconds
// returns a new promise
return new Promise(function(resolve, reject){
setTimeout(function(){ // when the time is up
resolve(); // change the promise to the fulfilled state
}, ms);
});
}
function getFive(){
// we're RETURNING the promise, remember, a promise is a wrapper over our value
return delay(100).then(function(){ // when the promise is ready
return 5; // return the value 5, promises are all about return values
})
}
// we _have_ to wrap it like this in the call site, we can't access the plain value
getFive().then(function(five){
document.body.innerHTML = five;
});
끝 - < 스니핏 >;!
이 스탠드 같은 기존 API 호출을 위한 작업을 수행할 수 있습니다.
function foo() {
// RETURN the promise
return fetch("/echo/json").then(function(response){
return response.json(); // process it inside the `then`
});
}
foo().then(function(response){
// access the value inside the `then`
})
그래서 이 작품을 그냥 잘 알려져 있다. # 39, ve, t # 39 의 값이 이미 우리가 배운 we& can& 복귀하십시오 비동기적입니다 페이징됩니다 우리 말과 수행할 처리 체인을 사용할 수 있습니다. 이제는 비동기 호출 반응이 반품해야 방법을 잘 알고 있습니다.
[생성기] (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function *) 가 돌아올 수 있는 기능을 es6 cxp 가운데 다시 시작 요점이지 그들은 dell. 이는 일반적으로 매우 유용한 시퀀스에만, 예를 들면 다음과 같습니다.
function* foo(){ // notice the star, this is ES6 so new browsers/node/io only
yield 1;
yield 2;
while(true) yield 3;
}
',' 가 반환하는 함수를 통해 충족되었으며 iterator e0100042.log 1.2,3.3,3.3 수 있는 이터레이션되는. 흥미로운 것은 그 동안 스스로 공간이 있어 한 가지 흥미로운 가능성을 열고 많이유 특정 사건.
그러나 이 다소 까다로운 매우 강력한 트릭 우릴 쓰기 비동기적입니다 코드에서 동기식 한다. 여러 가지 " runners"; 하지만 이 짧은 몇 줄의 코드를 작성하고, 그 중 하나는 당신꺼에요 할 수 있는 범위를 넘어서는 이 대답. # 39 의 'll be, i& Bluebird& 사용하여 # 39 와 같은 다른 래퍼' co '또는' q 'here, 프로미시스코우틴 수축됐는데 비동기'.
var foo = coroutine(function*(){
var data = yield fetch("/echo/json"); // notice the yield
// code here only executes _after_ the request is done
return data.json(); // data is defined
});
우리는 그 약속이 있는데, 이 방법은 다른 커넥터로부터 코루틴 되돌려줍니다 소비할 수 있습니다. 예를 들면 다음과 같습니다.
var main = coroutine(function*(){
var bar = yield foo(); // wait our earlier coroutine, it returns a promise
// server call done here, code below executes when done
var baz = yield fetch("/api/users/"+bar.userid); // depends on foo's result
console.log(baz); // runs after both requests done
});
main();
그러나 몇 가지 제안을 ES7 있는 지금, 이 것은 더 표준화했습니다 모두야 '약속' 있을 수 있습니다. 이건 그냥 " sugar"; (괜찮게 구문) 를 추가하여 ES6 제안 '위' 와 '' 키워드 async 기다리라. 위의 예는 있다.
async function foo(){
var data = await fetch("/echo/json"); // notice the await
// code here only executes _after_ the request is done
return data.json(); // data is defined
}
아직 약속이 되돌려줍니다 그대로:)
Ajax 잘못 사용하고 있습니다. 이 아이디어는 할꺼이나 아무 것도 하지 않고 손을 복귀하십시오 끕니까 뭔가 콜백 함수를 불렀으매 대행하고 있는 데이터를 데이터.
즉:
function handleData( responseData ) {
// Do what you want with the data
console.log(responseData);
}
$.ajax({
url: "hi.php",
...
success: function ( data, status, XHR ) {
handleData(data);
}
});
결국 아무것도 처리기에서 제출됩니다 다시 아무 것도 안. 한편, 아니면 아닌 합니다 인컨텍스트 끕니까 그리웠댔지 성공을 통해 데이터를 바로 인사이드라면 시작된다.
가장 간단한 방법은 자바스크립트 함수를 만들 수 있도록 '성공' 과 Ajax 호출 콜백하는.
function callServerAsync(){
$.ajax({
url: '...',
success: function(response) {
successCallback(response);
}
});
}
function successCallback(responseObj){
// Do something like read the response and show data
alert(JSON.stringify(responseObj)); // Only applicable to JSON response
}
function foo(callback) {
$.ajax({
url: '...',
success: function(response) {
return callback(null, response);
}
});
}
var result = foo(function(err, result){
if (!err)
console.log(result);
});
내아기마저도 오토메이티드 수신기마다 무서운 보이는, 손으로 그린 만화. 두 번째 이미지 때문에 '결과' 는 '코드에서 정의되지 않은' 이다.
1, [앙굴라이스] 사용하는 사람들에게 사용하여 이 상황을 처리할 수 있는 '약속'.
Here 썻냐면,
>. 공약 비동기적입니다 기능과 함께 여러 가지 기능을 사용하면 한 체인으로 어니스트 데 사용할 수 있습니다.
Here 도 좋은 설명을 찾을 수 있습니다.
[Docs] [4] 예를 찾아볼 수 있는 것 같습니다.
promiseB = promiseA.then(
function onSuccess(result) {
return result + 1;
}
,function onError(err) {
//Handle error
}
);
// promiseB will be resolved immediately after promiseA is resolved
// and its value will be the result of promiseA incremented by 1.
그러나 그 다음 예제를 보면 Angular2 '에서' 와 '' 을 (를) ' 권장됨 를 사용하여 Angular2' (한원소 공간) 이다.
search(term: string) {
return this.http
.get(`https://api.spotify.com/v1/search?q=${term}&type=artist`)
.map((response) => response.json())
.toPromise();
}
이런 식으로 소비할 수 있는
search() {
this.searchService.search(this.searchField.value)
.then((result) => {
this.result = result.artists.items;
})
.catch((error) => console.error(error));
}
원본 게시물로의 목마르겠구나 볼 그러나 타입스크립트 지원하지 않는 네이티브 es6 약속 사용하려는 경우 해당 플러그인에는 할 수 있습니다.
또한 이런 약속은 목마르겠구나 정의하십시오 슬라이드에서는 사양
여기에 대답을 할 수 있는 방법을 통해 대부분의 경우, 이 작업을 할 때, 하지만 가끔 들려온다 단일 비동기 비동기 작업에 엔트리여야 각 작업공간에서 어레이나 다른 목록 같은 구조. The temptation 은 이 작업을 수행할 수 있습니다.
// WRONG
var results = [];
theArray.forEach(function(entry) {
doSomethingAsync(entry, function(result) {
results.push(result);
});
});
console.log(results); // E.g., using them, returning them, etc.
예: <! - begin 스니핏: js 숨기십시오: 진정한 콘솔: 진정한 바벨. > 거짓값 -;
// WRONG
var theArray = [1, 2, 3];
var results = [];
theArray.forEach(function(entry) {
doSomethingAsync(entry, function(result) {
results.push(result);
});
});
console.log("Results:", results); // E.g., using them, returning them, etc.
function doSomethingAsync(value, callback) {
console.log("Starting async operation for " + value);
setTimeout(function() {
console.log("Completing async operation for " + value);
callback(value * 2);
}, Math.floor(Math.random() * 200));
}
.as-console-wrapper {
max-height: 100% !important;
}
끝 - < 스니핏 >;! 이처럼 doesn& # 39 건, t, t 작동합니까 도주메트링라인스 '에서' 콜백 haven& # 39 시간은 아직 실행하십시오 의해 you& # 39, re 사용하려는 결과. 따라서 어레이에서는 수행하고자 하는 경우 (또는 list of some kind) 및 비동기 운영체 각 항목마다, 두 가지 옵션이 있습니다. 작전을 수행할 평행광 (중첩되도록), 또는 시리즈 (줄줄이 순서대로).
var results = [];
var expecting = theArray.length;
theArray.forEach(function(entry, index) {
doSomethingAsync(entry, function(result) {
results[index] = result;
if (--expecting === 0) {
// Done!
console.log("Results:", results); // E.g., using the results
}
});
});
예: <! - begin 스니핏: js 숨기십시오: 진정한 콘솔: 진정한 바벨. > 거짓값 -;
var theArray = [1, 2, 3];
var results = [];
var expecting = theArray.length;
theArray.forEach(function(entry, index) {
doSomethingAsync(entry, function(result) {
results[index] = result;
if (--expecting === 0) {
// Done!
console.log("Results:", results); // E.g., using the results
}
});
});
function doSomethingAsync(value, callback) {
console.log("Starting async operation for " + value);
setTimeout(function() {
console.log("Completing async operation for " + value);
callback(value * 2);
}, Math.floor(Math.random() * 200));
}
.as-console-wrapper {
max-height: 100% !important;
}
끝 - < 스니핏 >;!
function doSomethingWith(theArray, callback) {
var results = [];
var expecting = theArray.length;
theArray.forEach(function(entry, index) {
doSomethingAsync(entry, function(result) {
results[index] = result;
if (--expecting === 0) {
// Done!
callback(results);
}
});
});
}
doSomethingWith(theArray, function(results) {
console.log("Results:", results);
});
예: <! - begin 스니핏: js 숨기십시오: 진정한 콘솔: 진정한 바벨. > 거짓값 -;
function doSomethingWith(theArray, callback) {
var results = [];
var expecting = theArray.length;
theArray.forEach(function(entry, index) {
doSomethingAsync(entry, function(result) {
results[index] = result;
if (--expecting === 0) {
// Done!
callback(results);
}
});
});
}
doSomethingWith([1, 2, 3], function(results) {
console.log("Results:", results);
});
function doSomethingAsync(value, callback) {
console.log("Starting async operation for " + value);
setTimeout(function() {
console.log("Completing async operation for " + value);
callback(value * 2);
}, Math.floor(Math.random() * 200));
}
.as-console-wrapper {
max-height: 100% !important;
}
끝 - < 스니핏 >;!
function doSomethingWith(theArray) {
return new Promise(function(resolve) {
var results = [];
var expecting = theArray.length;
theArray.forEach(function(entry, index) {
doSomethingAsync(entry, function(result) {
results[index] = result;
if (--expecting === 0) {
// Done!
resolve(results);
}
});
});
});
}
doSomethingWith(theArray).then(function(results) {
console.log("Results:", results);
});
function doSomethingWith(theArray) {
return new Promise(function(resolve) {
var results = [];
var expecting = theArray.length;
theArray.forEach(function(entry, index) {
doSomethingAsync(entry, function(result) {
results[index] = result;
if (--expecting === 0) {
// Done!
resolve(results);
}
});
});
});
}
doSomethingWith([1, 2, 3]).then(function(results) {
console.log("Results:", results);
});
function doSomethingAsync(value, callback) {
console.log("Starting async operation for " + value);
setTimeout(function() {
console.log("Completing async operation for " + value);
callback(value * 2);
}, Math.floor(Math.random() * 200));
}
.as-console-wrapper {
max-height: 100% !important;
}
끝 - < 스니핏 >;!
function doSomethingWith(theArray) {
return Promise.all(theArray.map(function(entry) {
return doSomethingAsync(entry);
}));
}
doSomethingWith(theArray).then(function(results) {
console.log("Results:", results);
});
만약 알잖나 도주메트링라인스 '가' 제 2 차, 3 차 '를 바로 매핑해야 무시하시겠습니까 인수, 그냥 지나칠 수 있습니다' ('지도' 페이징됩니다 그 콜백하는 첫 번째, 세 개의 인수만 기울이나 백성들이 사용하는 대부분의 시간을):
function doSomethingWith(theArray) {
return Promise.all(theArray.map(doSomethingAsync));
}
doSomethingWith(theArray).then(function(results) {
console.log("Results:", results);
});
예: <! - begin 스니핏: js 숨기십시오: 진정한 콘솔: 진정한 바벨. > 거짓값 -;
function doSomethingWith(theArray) {
return Promise.all(theArray.map(doSomethingAsync));
}
doSomethingWith([1, 2, 3]).then(function(results) {
console.log("Results:", results);
});
function doSomethingAsync(value) {
console.log("Starting async operation for " + value);
return new Promise(function(resolve) {
setTimeout(function() {
console.log("Completing async operation for " + value);
resolve(value * 2);
}, Math.floor(Math.random() * 200));
});
}
.as-console-wrapper {
max-height: 100% !important;
}
끝 - < 스니핏 >;! 참고로 '와' 약속을 지키는 보정됩니다 프로미즈리얼 결과를 배열입니다 모든 공약을 you give it 의 경우 또는 모든 약속을 지키는 거부됩니다 해결됨으로 때 이런 약속은 첫 you give it 부인하고 있습니다.
function doSomethingWith(theArray, callback) {
var results = [];
doOne(0);
function doOne(index) {
if (index < theArray.length) {
doSomethingAsync(theArray[index], function(result) {
results.push(result);
doOne(index + 1);
});
} else {
// Done!
callback(results);
}
}
}
doSomethingWith(theArray, function(results) {
console.log("Results:", results);
});
function doSomethingWith(theArray, callback) {
var results = [];
doOne(0);
function doOne(index) {
if (index < theArray.length) {
doSomethingAsync(theArray[index], function(result) {
results.push(result);
doOne(index + 1);
});
} else {
// Done!
callback(results);
}
}
}
doSomethingWith([1, 2, 3], function(results) {
console.log("Results:", results);
});
function doSomethingAsync(value, callback) {
console.log("Starting async operation for " + value);
setTimeout(function() {
console.log("Completing async operation for " + value);
callback(value * 2);
}, Math.floor(Math.random() * 200));
}
.as-console-wrapper {
max-height: 100% !important;
}
끝 - < 스니핏 >;!
async function doSomethingWith(theArray) {
const results = [];
for (const entry of theArray) {
results.push(await doSomethingAsync(entry));
}
return results;
}
doSomethingWith(theArray).then(results => {
console.log("Results:", results);
});
예: <! - begin 스니핏: js 숨기십시오: 진정한 콘솔: 진정한 바벨. > 거짓값 -;
async function doSomethingWith(theArray) {
const results = [];
for (const entry of theArray) {
results.push(await doSomethingAsync(entry));
}
return results;
}
doSomethingWith([1, 2, 3]).then(function(results) {
console.log("Results:", results);
});
function doSomethingAsync(value) {
console.log("Starting async operation for " + value);
return new Promise(function(resolve) {
setTimeout(function() {
console.log("Completing async operation for " + value);
resolve(value * 2);
}, Math.floor(Math.random() * 200));
});
}
.as-console-wrapper {
max-height: 100% !important;
}
끝 - < 스니핏 >;!
function doSomethingWith(theArray) {
return theArray.reduce(function(p, entry) {
return p.then(function(results) {
return doSomethingAsync(entry).then(function(result) {
results.push(result);
return results;
});
});
}, Promise.resolve([]));
}
doSomethingWith(theArray).then(function(results) {
console.log("Results:", results);
});
예: <! - begin 스니핏: js 숨기십시오: 진정한 콘솔: 진정한 바벨. > 거짓값 -;
function doSomethingWith(theArray) {
return theArray.reduce(function(p, entry) {
return p.then(function(results) {
return doSomethingAsync(entry).then(function(result) {
results.push(result);
return results;
});
});
}, Promise.resolve([]));
}
doSomethingWith([1, 2, 3]).then(function(results) {
console.log("Results:", results);
});
function doSomethingAsync(value) {
console.log("Starting async operation for " + value);
return new Promise(function(resolve) {
setTimeout(function() {
console.log("Completing async operation for " + value);
resolve(value * 2);
}, Math.floor(Math.random() * 200));
});
}
.as-console-wrapper {
max-height: 100% !important;
}
끝 - < 스니핏 >;! 덜 드와이치 번거로운 와 ES2015+ 누르십시보 총괄하였습니다:
function doSomethingWith(theArray) {
return theArray.reduce((p, entry) => p.then(results => doSomethingAsync(entry).then(result => {
results.push(result);
return results;
})), Promise.resolve([]));
}
doSomethingWith(theArray).then(results => {
console.log("Results:", results);
});
예: <! - begin 스니핏: js 숨기십시오: 진정한 콘솔: 진정한 바벨. > 거짓값 -;
function doSomethingWith(theArray) {
return theArray.reduce((p, entry) => p.then(results => doSomethingAsync(entry).then(result => {
results.push(result);
return results;
})), Promise.resolve([]));
}
doSomethingWith([1, 2, 3]).then(function(results) {
console.log("Results:", results);
});
function doSomethingAsync(value) {
console.log("Starting async operation for " + value);
return new Promise(function(resolve) {
setTimeout(function() {
console.log("Completing async operation for " + value);
resolve(value * 2);
}, Math.floor(Math.random() * 200));
});
}
.as-console-wrapper {
max-height: 100% !important;
}
끝 - < 스니핏 >;!
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope,$http) {
var getJoke = function(){
return $http.get('http://api.icndb.com/jokes/random').then(function(res){
return res.data.value;
});
}
getJoke().then(function(res) {
console.log(res.joke);
});
});
이것은 plnkr:*
http://embed.plnkr.co/XlNR7HpCaIhJxskMJfSg/
(function(){
async function getJoke(){
let response = await fetch('http://api.icndb.com/jokes/random');
let data = await response.json();
return data.value;
}
getJoke().then((joke) => {
console.log(joke);
});
})();
이 두 가지 방법 중 하나는 바로 데이터를 저장할 수 있는 곳도 # 39 에 사용되는 개념 또는 바인딩하면 that& 많은 새 자바스크립트 프레임워크와도 멋지구리해요 사용할 수 있습니다.
그래서 못하며창조된 사용하는 경우 각, 또는 다른 두 가지 방법으로 대응할 수 있는 데이터 저장 또는 프레임워크와도 바인딩하면 개념을 쉽게 그 결과 이 문제는 단순히 고정식입니다 당신꺼에요 말을해야합니다 너회의 정의되지 않은 '의' 는 '1 단계, 그래서 당신은 attaboy 받을 때까지 정의되지 않은 결과 =' 데이터 관심용 확보하십시오 이를 즉시 결과를 가져올 수 있는 새로운 값으로 지정받습니다 업데이트되어야 및 Ajax 응답이 가능하다.
하지만 어떻게 할 수 있는 jQuery 또는 순수 javascript 질문과대답 때 예를 들어 이 질문이 있습니까?
예를 들어 네 경우엔 jQuery , 사용하는 이 같은 일이 할 수 있습니다.
$(document).ready(function(){
function foo() {
$.ajax({url: "api/data", success: function(data){
fooDone(data); //after we have data, we pass it to fooDone
}});
};
function fooDone(data) {
console.log(data); //fooDone has the data and console.log it
};
foo(); //call happens here
});
다른 외곽진입 반환되기를 비동기적입니다 에서 값을 저장할 수 있는 기능은 전달하십시오 객체에는 결과를 비동기 기능.
같은 예를 들어보겠습니다.
var async = require("async");
// This wires up result back to the caller
var result = {};
var asyncTasks = [];
asyncTasks.push(function(_callback){
// some asynchronous operation
$.ajax({
url: '...',
success: function(response) {
result.response = response;
_callback();
}
});
});
async.parallel(asyncTasks, function(){
// result is available after performing asynchronous operation
console.log(result)
console.log('Done');
});
나는 그 동안 값을 저장할 수 있는 '사용' 객체에는 비동기적입니다 운영할 수 있다. 그 후에도 비동기적입니다 죠브 사용할 수 있습니다
내가 이 외곽진입 많이유. 내가 얼마나 잘 알고 있는 이 결과를 통해 약간만이라도 하는 외곽진입 작동됨 와이어링 뒤로를 연속적입니다 모듈에서는 도전이다.
말과 동시에 표현할 수 있는 것은 대부분의 경우 콜백 작동합니다 통증이 개/후면 다음과 같은 항목을
if (!name) {
name = async1();
}
async2(name);
async1(name, callback) {
if (name)
callback(name)
else {
doSomething(callback)
}
}
async1(name, async2)
작은 참조용이므로 okay 동안에는 많은 경우 it gets 귀찮은 및 오류 처리 비슷한 사례가 있었다.
'물고기' 이 문제를 해결하는 데 도움이 됩니다.
var Fiber = require('fibers')
function async1(container) {
var current = Fiber.current
var result
doSomething(function(name) {
result = name
fiber.run()
})
Fiber.yield()
return result
}
Fiber(function() {
var name
if (!name) {
name = async1()
}
async2(name)
// Make any number of async calls from here
}
프로젝트 [here] 체크아웃합니다 수 있습니다 (https://github.com/laverdet/node-fibers).
다음 예제에서는 기록되었으므로 나는 방법을 보여
이 작업 비유하사 독립된. 또 '윈도' 스믈하트프리퀘스트 객체를 사용하는 간단한 요청 객체에는 정의할 수 있다. 간단한 함수를 정의할 수 있는 여러 공약을 완료됨으로 기다려야 할 것으로 보인다.
컨텍스트입니다. 이 비유하사 쿼리하지 스포티파이 웹 API 종료점 검색하기 위해 주어진 집합을 '재생' 객체에는 쿼리하지 문장열:
[
"search?type=playlist&q=%22doom%20metal%22",
"search?type=playlist&q=Adele"
]
각 항목에 대해 '-' 는 블록, 구문 분석 결과, 새로운 약속하나요 불지옥의 에스쿠션브록 예약하십시오 결과에 따라 새로운 약속, 즉 '사용자' 객체에는 어레이입니다 목록을 스포티파이, 실행할 수 있는 '콜' 새로운 HTTP 에스쿠션프로피레브로크 비동기적으로.
그런 다음 네스트된 약속하나요 구조를 볼 수 있는 여러 HTTP 요청, 이 (가) 와 완전히 비동기적입니다 네스트된 힘을 통해 각 서브셋에 프로미즈리얼 페이징됩니다 '결과'.
-H "Authorization: Bearer {your access token}"
따라서 액세스 할 수 있습니다 다음 들어 실행하십시오 모세야 네 토큰인지 요청 헤더도:
<! - begin 스니핏: js 숨기십시오: > 거짓값 -;
var spotifyAccessToken = "YourSpotifyAccessToken";
var console = {
log: function(s) {
document.getElementById("console").innerHTML += s + "<br/>"
}
}
// Simple XMLHttpRequest
// based on https://davidwalsh.name/xmlhttprequest
SimpleRequest = {
call: function(what, response) {
var request;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
request = new XMLHttpRequest();
} else if (window.ActiveXObject) { // Internet Explorer
try {
request = new ActiveXObject('Msxml2.XMLHTTP');
}
catch (e) {
try {
request = new ActiveXObject('Microsoft.XMLHTTP');
} catch (e) {}
}
}
// State changes
request.onreadystatechange = function() {
if (request.readyState === 4) { // Done
if (request.status === 200) { // Complete
response(request.responseText)
}
else
response();
}
}
request.open('GET', what, true);
request.setRequestHeader("Authorization", "Bearer " + spotifyAccessToken);
request.send(null);
}
}
//PromiseAll
var promiseAll = function(items, block, done, fail) {
var self = this;
var promises = [],
index = 0;
items.forEach(function(item) {
promises.push(function(item, i) {
return new Promise(function(resolve, reject) {
if (block) {
block.apply(this, [item, index, resolve, reject]);
}
});
}(item, ++index))
});
Promise.all(promises).then(function AcceptHandler(results) {
if (done) done(results);
}, function ErrorHandler(error) {
if (fail) fail(error);
});
}; //promiseAll
// LP: deferred execution block
var ExecutionBlock = function(item, index, resolve, reject) {
var url = "https://api.spotify.com/v1/"
url += item;
console.log( url )
SimpleRequest.call(url, function(result) {
if (result) {
var profileUrls = JSON.parse(result).playlists.items.map(function(item, index) {
return item.owner.href;
})
resolve(profileUrls);
}
else {
reject(new Error("call error"));
}
})
}
arr = [
"search?type=playlist&q=%22doom%20metal%22",
"search?type=playlist&q=Adele"
]
promiseAll(arr, function(item, index, resolve, reject) {
console.log("Making request [" + index + "]")
ExecutionBlock(item, index, resolve, reject);
}, function(results) { // Aggregated results
console.log("All profiles received " + results.length);
//console.log(JSON.stringify(results[0], null, 2));
///// promiseall again
var ExecutionProfileBlock = function(item, index, resolve, reject) {
SimpleRequest.call(item, function(result) {
if (result) {
var obj = JSON.parse(result);
resolve({
name: obj.display_name,
followers: obj.followers.total,
url: obj.href
});
} //result
})
} //ExecutionProfileBlock
promiseAll(results[0], function(item, index, resolve, reject) {
//console.log("Making request [" + index + "] " + item)
ExecutionProfileBlock(item, index, resolve, reject);
}, function(results) { // aggregated results
console.log("All response received " + results.length);
console.log(JSON.stringify(results, null, 2));
}
, function(error) { // Error
console.log(error);
})
/////
},
function(error) { // Error
console.log(error);
});
<div id="console" />
끝 - < 스니핏 >;!
나는 이 솔루션을 [here] [4] 폭넓게 논의했다.
[4]: # 36537774 https://stackoverflow.com/questions/36536245/how-to-search-for-a-user-by-name-using-spotify-web-api/36537774
이것은 매우 단순하다.
(async function(){
var response = await superagent.get('...')
console.log(response)
})()
[기다리고 있는 지원되며, 현재의 모든 브라우저와 노드입니다 8] (http://caniuse.com/ # 기다리는 검색 =)
function foo(){
// do something
return 'wohoo';
}
let bar = foo(); // bar is 'wohoo' here
이제 조금 let& # 39 의 추가 도입해 리틀이에요 지연입니다 트위스트, 따라서 모든 코드는 & # 39 의 기능을 않습니다를 finished& # 39;; 순서대로. 이에 따라 비동기식 비헤이비어를 거역한다면 에뮬레이트합니다 함수.
function foo(){
setTimeout( ()=>{
return 'wohoo';
}, 1000 )
}
let bar = foo() // bar is undefined here
그래서 그냥 것으로 예상했지만, 그 기능을 여깄군 지연입니다 깨고! 하지만 정확히 어떻게 됐어? 뭐, 사실 매우 로털 쳐다보거라 it& # 39 의 경우 코드. 함수가 실행 시 () ',' 푸 (카타시안 반환되었습니다 값이 정의되지 않은 ''), 아무것도아니야 되돌려줍니다 않지만, & # 39, 타이머, 어떤 함수 시작 후 실행하므로 1s 반환되기를 wohoo& # 39;. 하지만 보시다시피, s # 39 는 foo 의 값을 that& 대입된 표시줄에는 아닌 다른 사항은요 나중에 나오는 즉시 반환되었습니다 stuff ().
정말 약속하나요 의심하였더라 무슨뜻이냐믄: 해당 함수가 무슨뜻이냐믄 보장 없이 향후 it gets 출력입니다 제공할 수 있습니다. 그래서 let& # 39 에 대한 우리의 작은 위 문제를 실제로 확인해 보십시오.
function foo(){
return new Promise( (resolve, reject) => { // I want foo() to PROMISE me something
setTimeout ( function(){
// promise is RESOLVED , when execution reaches this line of code
resolve('wohoo')// After 1 second, RESOLVE the promise with value 'wohoo'
}, 1000 )
})
}
let bar ;
foo().then( res => {
bar = res;
console.log(bar) // will print 'wohoo'
});
즉, 요약하면 - ajax 기반의 비동기식 문제를 다루기 위해 같은 기능을 사용할 수 있습니다 '가치' 약속을 해결하십시오 페이징됩니다 상술합니다. (이것은 않으려면 반환). 값을 반환하는 대신 카타시안, 간단히 해결할 수 있습니다, 비동기 총괄하였습니다.
'약속' 을 사용하여 다음 / catch 별도로, 한 번 더 외곽진입 작동합니까 존재한다. 이 의견은 비동기 함수 인정할 때까지 기다린 후 공약을 해결하십시오 다음 줄로 이동하기 전에 코드. # 39 의 it& 그냥 '약속' 후드 아래에 갖추고 있지만, 여전히 다른 구문 외곽진입. 더 비교 할 것을 찾을 수 있습니다 (아래 참조).
function saveUsers(){
getUsers()
.then(users => {
saveSomewhere(users);
})
.catch(err => {
throw err;
})
}
async function saveUsers(){
try{
let users = await getUsers()
saveSomewhere(users);
}
catch(err){
throw err;
}
}
이 사용자 정의 라이브러리 (사용해 쓰여진 약속하나요) 원격 호출 만드는 데 사용할 수 있습니다.
function $http(apiConfig) {
return new Promise(function (resolve, reject) {
var client = new XMLHttpRequest();
client.open(apiConfig.method, apiConfig.url);
client.send();
client.onload = function () {
if (this.status >= 200 && this.status < 300) {
// Performs the function "resolve" when this.status is equal to 2xx.
// Your logic here.
resolve(this.response);
}
else {
// Performs the function "reject" when this.status is different than 2xx.
reject(this.statusText);
}
};
client.onerror = function () {
reject(this.statusText);
};
});
}
간단한 사용 예제:
$http({
method: 'get',
url: 'google.com'
}).then(function(response) {
console.log(response);
}, function(error) {
console.log(error)
});
또 다른 방법은 실행 코드를 통해 순차인지 집행관 산린제스.
그 결과 '에' 는 약속을 하고, 모든 데이터를 순차적으로 산린제스 평가하십시오 약속하나요 속성:
<! - begin 스니핏: js 숨기십시오: 거짓값 콘솔: 진정한 바벨. > 거짓값 -;
function synchronousCode() {
var getURL = function(url) {
return window.fetch(url).data.text().data;
};
var url = 'https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js';
console.log('received bytes:',getURL(url).length);
};
nsynjs.run(synchronousCode,{},function(){
console.log('synchronousCode done');
});
<script src="https://rawgit.com/amaksr/nsynjs/master/nsynjs.js"></script>
끝 - < 스니핏 >;!
1 단계. 랩 (wrap) 에 있는 함수를 콜백하는 산린제스 인식 래퍼 (있으면 프로미시프리드 버전, 이 단계를 건너뛸 수 있습니다):
var ajaxGet = function (ctx,url) {
var res = {};
var ex;
$.ajax(url)
.done(function (data) {
res.data = data;
})
.fail(function(e) {
ex = e;
})
.always(function() {
ctx.resume(ex);
});
return res;
};
ajaxGet.nsynjsHasCallback = true;
2 단계. 동일팔레트에 동기식 논리를 기능:
function process() {
console.log('got data:', ajaxGet(nsynjsCtx, "data/file1.json").data);
}
3 단계. 기능을 통해 동기식 분할합니다 실행하십시오 산린제스:
nsynjs.run(process,this,function () {
console.log("synchronous function finished");
});
산린제스 평가하여 그 결과에 따라 일부 실행 속도가 느린 경우 모든 종합유선방송사업자 (so) 와 표현식에서는 단계별, 일시 정지 기능을 사용하지 않는 준비되었음.
더 많은 예를 있습니다. https://github.com/amaksr/nsynjs/tree/master/examples
>. Js 는 단일 스레드.
브라우저 세 부분으로 나눌 수 있습니다.
이벤트 루프
웹 API
이벤트 대기열은
이벤트 루프를 런입니다 영생하리니 이리에 사람이었는가부텀 대한 무한한 루프지 이벤트 대기열은 대화상자에서는 끼워졌는지 사용자의 모든 기능이 일부 이벤트 (예: 클릭) 이는 하나씩 준비하고 있는 이 기능을 넣을 수행되 대기열 및 이벤트 루프를 실행하십시오 _자/하이픈 뒤 향후 it 및 자체 하나는 한 것으로 보인다. 즉, 함수 실행 기능, 시작 전에 한 큐에 있는 실행될 때까지 doesn& t # 39 의 이벤트 루프지
그럼 지금부터 싱크탱크인 우리는 두 가지 기능을 서버에서 데이터를 얻을 수 있고, 다른 하나는 끼워졌는지 대기열의 데이터 위해 사용됩니다. 우리는 이 큐에 있는 덮어쓴 티리스트라다 끼워졌는지 세르베르퀘스트 () 함수 () 함수. 함수 호출이 서버로 이벤트 루프를 세르베르퀘스트 댁이라면 만들어 집니다 서버에서 데이터를 얻기 위해 우리가 얼마나 많은 시간이 걸릴 수 있는지 알 수가 없다 그래서 이 과정은 시간이 걸릴 것으로 바쁜 우리 하나님은 우리의 이벤트 페이지, 웹 API 의 루프 카타시안 내어쓰기는 that& # 39 이 계약을 맺을 수 있는 역할을 할 수 있도록 무료 이벤트 루프는 루프 및 서버 시행하십시오 event 에서 이 기능을 실행할 수 있습니다 다음 함수은 큐에서. 그러나 댁이라면 루프 () 는 다음 기능을 하는 it 의 데이터를 사용할 수 없기 때문에 대기열은 티리스트라다 댁이라면 그들이실천하는 및 실행 종료 때까지 계속 다음 함수은 대기열은. (이것은 우리가 할 수 있는 데이터를 비동기 호출 이리에 호출됨 인도되니 we get something else)
이제 우리는 한 때, 우리는 우리의 세르베르퀘스트 () 함수는 코드를 API 는 웹 서버의 데이터를 물러서요 복귀하십시오 문을 큐에 있는 밉니다 대기열은 말. 끼워졌는지 dell. 끝나는 대로 해당 데이터를 얻을 수 없기 때문에 우리 대기열은 함수은 대기열은 활용 수 없다 이 남아 있을 수 없습니다 에서 비동기 Call. 뭔가 반품하십시오 ata.Thus 제공하기로 약속했다.
이것은 또는 카타시안 솔루션을 콜백하는 약속하나요.
function doAjax(callbackFunc, method, url) {
var xmlHttpReq = new XMLHttpRequest();
xmlHttpReq.open(method, url);
xmlHttpReq.onreadystatechange = function() {
if (xmlHttpReq.readyState == 4 && xmlHttpReq.status == 200) {
callbackFunc(xmlHttpReq.responseText);
}
}
xmlHttpReq.send(null);
}
내 코드를 호출됨 등 정보기술 (it)
function loadMyJson(categoryValue){
if(categoryValue==="veg")
doAjax(print,"GET","http://localhost:3004/vegetables");
else if(categoryValue==="fruits")
doAjax(print,"GET","http://localhost:3004/fruits");
else
console.log("Data not found");
}
여기에 새로운 방법으로 ECMA (2016/17) 읽을 수 있도록 지원하는 비동기 호출 (@Felix 클링 오토메이티드 위) https://stackoverflow.com/a/14220323/7579856