什么是ES6承诺相当于jQuery Deferred' s```

时间:2015-10-01 08:02:08

标签: javascript jquery es6-promise

我有以下内容:

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

getUser返回一个jQuery Deferred对象。

我从this article了解到我可以使用Promise.resolve将Deferred对象转换为本机Promise,所以我可以写

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

虽然Promise API没有提供always方法,但我想知道应该如何处理。

是否如下?

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

2 个答案:

答案 0 :(得分:20)

我认为您正在寻找以下内容:

 Promise.resolve(getUser("foo"))
  .then(handleSuccess, handleError)
  .then(tidyUp)
始终会调用tidyUp。有关完整示例,请参阅以下jsbin:http://jsbin.com/lujubu/edit?html,js,console,output

答案 1 :(得分:3)

使用always函数作为resolve reject的处理程序,以确保始终调用它。

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