创建一个成功/错误的承诺,例如像ajax

Creating a promise with success / error for example like ajax

本文关键字:承诺 ajax 错误 成功 一个 创建      更新时间:2023-09-26

我正在尝试弄清楚如何使承诺与成功和错误回调一起工作,例如在 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);
});

我应该怎么做?

承诺只是使用不同的术语,您的.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;

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和其他几个库在某种程度上遵循这一点。