2015-10-01 18 views
23

Tôi có một cái gì đó như sau:ES6 Promise tương đương với jQuery Deferred 'luôn luôn` là gì?

getUser("foo").then(handleSuccess, handleError).always(tidyUp); 

getUser trả về một đối tượng thu nhập hoãn lại jQuery.

Tôi hiểu từ this article mà tôi có thể chuyển đổi các đối tượng thu nhập hoãn lại đến một Promise có nguồn gốc sử dụng Promise.resolve, vì vậy tôi có thể viết

Promise.resolve(getUser("foo")) 
    .then(handleSuccess) 
    .catch(handleError) 

Các Promise API không cung cấp một phương pháp always mặc dù, vì vậy tôi tự hỏi như thế nào cần được xử lý.

Có phải như sau không?

Promise.resolve(getUser("foo")) 
    .then(handleSuccess) 
    .then(tidyUp) 
    .catch(handleError) 
    .then(tidyUp) 

Trả lời

19

Tôi nghĩ rằng đây là những gì bạn đang tìm kiếm:

Promise.resolve(getUser("foo")) 
    .then(handleSuccess, handleError) 
    .then(tidyUp) 

tidyUp sẽ luôn gọi. Xem jsbin sau cho ví dụ đầy đủ: http://jsbin.com/lujubu/edit?html,js,console,output

+4

Vâng, đó sẽ làm việc nhờ. Bạn cũng làm cho tôi nhận ra rằng tôi cũng có thể chỉ làm 'Promise.resolve (getUser (" foo ")). Sau đó (handleSuccess) .catch (handleError) .then (tidyUp)', tức là giữ 'catch'. – user5325596

3

Sử dụng chức năng always của bạn như là handler cho resolvereject để đảm bảo nó sẽ luôn luôn được gọi.

function getUser(result) { 
    switch (result) { 
     case 'good': 
      return Promise.resolve(); 

     case 'bad': 
      return Promise.reject(); 

     case 'ugly': 
      return new Promise(() => { throw new Error() }) 
    } 
} 

function handleSuccess() { console.log('success') } 
function handleError() { console.log('error') } 
function tidyUp() { console.log('all tidy now') } 


Promise.resolve(getUser('good')) 
    .then(handleSuccess) 
    .catch(handleError) 
    .then(tidyUp, tidyUp); 

Promise.resolve(getUser('bad')) 
    .then(handleSuccess) 
    .catch(handleError) 
    .then(tidyUp, tidyUp); 

Promise.resolve(getUser('ugly')) 
    .then(handleSuccess) 
    .catch(handleError) 
    .then(tidyUp, tidyUp); 

// success 
// error 
// error 
// all tidy now 
// all tidy now 
// all tidy now 

Promise API Reference

Các vấn đề liên quan