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

What is the ES6 Promise equivalent of jQuery Deferred's 'always`?

本文关键字:always Deferred ES6 承诺 相当于 jQuery 什么      更新时间:2023-09-26

我有如下内容:

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

getUser返回一个jQuery Deferred对象。

我从本文中了解到,我可以使用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)

我认为以下是你要找的:

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

tidyUp将始终被调用。完整示例参见下面的jsbin: http://jsbin.com/lujubu/edit?html,js,console,output

使用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