2014-12-25 4 views
0

ajax에서와 같이 성공 및 오류 콜백을 사용하여 약속을 수행하는 방법을 파악하려고합니다.예 : Ajax와 같이 성공/오류가있는 약속 만들기

나는 다음과 같은 약속을했다 :

var promise = new Promise(function(success, error) { 
     if (true) { 
     success("Stuff worked!"); 
     } 
     else { 
      error(Error("It broke")); 
     } 
    }); 
    promise.then(function(result) 
    { 
     console.log(result); 
    }, function(err) 
    { 
     console.log(err); 
    }); 

나는 그것이 이런 식으로 작업 할 :

promise.success(function(response) 
{ 
    console.log(response); 
}).error(functin(err) 
{ 
    console.log(err); 
}); 

내가 생각하고는 할까?

답변

0

successerror는 다음과 같은 작업을 수행 단순히 문법 설탕입니다 같은 것을 할 수 있습니다

function CustomPromise(callback){ 
    this.promise = new Promise(callback); 
} 

// Success and error are merely shorthand functions 
CustomPromise.prototype.success = function(callback){ 
    this.promise.then(callback,null); 
}; 

CustomPromise.prototype.error = function(callback){ 
    this.promise.then(null,callback); 
} 

// Expose the rest of the promise interface, especially `then` and `catch` 

원시 Promise 프로토 타입이 확장되지 않았 음을 유의하십시오.

나는 이것이 약속을위한 "표준"인터페이스가되었으므로 then(success,error)을 계속 사용하는 것이 좋습니다. jQuery와 몇몇 다른 libs는 어느 정도까지 이것을 따른다.

+0

이것이 그랬지만, success/error 함수 뒤에'return this;'를 사용하여 그들을 연결할 수 있다는 것을 기억하십시오. –

+1

네이티브 약속은 하위 클래스가 아닙니다. 스펙을 잘 구현하지 않아 가까운 장래에 브라우저에서 깨질 것입니다. 또한'.prototype = Object.create (Promise.prototype)'과'Promise (this)'를 호출해야합니다. - 다시 말하지만, 이것은 본래의 약속이해야한다고 말하고 있지만 그렇게하지 않는 것입니다. 또한 약속의 기본 프로토 타입을 확장하는 것이 좋지 않은 생각이지만 주관적입니다. –

2

약속은 다른 용어로 간단히 사용합니다. .success.error.then.catch으로 번역됩니다. 당신이 정말로이 (하지 마십시오) 원하는 경우

promise 
    .then(function(value) { 
     console.log(value); 
    }) 
    .catch(function(err) { 
     console.log(err); 
    }); 

, 당신은

Promise.prototype.success = Promise.prototype.success || Promise.prototype.then; 
Promise.prototype.error = Promise.prototype.error || Promise.prototype.catch; 
+0

그래서 $ .post는 어떻게 작동합니까? 어떤 생각? –

+2

@DalaiLama jQuery는 ECMAScript 또는 Promises A + 사양을 따르지 않는 다른 (나쁜) 종류의 약속을 사용합니다. 나는 이것을 예제로 삼지 않을 것이다. –

+0

좋아, Jquery뿐. 예를 들어 Angular $ http post를 사용하십시오. 나는 아직도 그것을 테스트 할 필요가있다. 나는 그것의 행동을 조롱 할 필요가있다. 코드에서 사용하지 않을 것이므로 테스트 해 보겠습니다. –

관련 문제