何时拒绝/解决承诺 [英] When to reject/resolve a promise

查看:38
本文介绍了何时拒绝/解决承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在考虑什么时候需要拒绝一个承诺.我发现了几个关于这个主题的问题,但找不到正确的答案.我什么时候应该拒绝承诺?

I am thinking about when exactly I need to reject a promise. I found a couple of questions regarding this topic, but could not find a proper answer. When should I reject a promise?

这篇文章http://howtonode.org/6666a4b74d7434144cff717c36e7a/promises/说:

This article http://howtonode.org/6666a4b74d7434144cff717c828be2c3953d46e7/promises says:

  • 解析:成功的 Promise 被解析",它调用正在等待的成功侦听器并记住为附加的未来成功侦听器解析的值.分辨率与返回值相关.
  • Reject:当遇到错误情况时,Promise 会被拒绝",它会调用正在等待的错误侦听器并记住被拒绝的值,以供将来附加的错误侦听器使用.拒绝与抛出的异常相关.

这是原则指南吗?那个只有在发生异常时才拒绝承诺?

Is this the principle guideline? That one only reject a promise if an exception occured?

但是对于像

findUserByEmail()

我希望函数返回一个用户,这样我就可以在不验证结果的情况下继续链

I'd would expect the function to return a user, so that I can continue the chain without verifying the result

findUserByEmail()
    .then(sendWelcomeBackEmail)
    .then(doSomeNiceStuff)
    .then(etc..)

什么是最佳/常见做法?

What are best / common practises?

推荐答案

一般来说,你可以认为拒绝类似于同步throw,而实现类似于同步return.每当函数以某种方式不成功时,您应该拒绝.这可能是超时、网络错误、错误输入等.

In general you can think of rejecting as being analogous to a synchronous throw and fulfilling as being analogous to a synchronous return. You should reject whenever the function is unsuccessful in some way. That could be a timeout, a network error, incorrect input etc. etc.

拒绝承诺,就像抛出异常一样,对于控制流很有用.它不必代表真正意外的错误;它可以代表您完全预料到并处理的问题:

Rejecting a promise, just like throwing an exception, is useful for control flow. It doesn't have to represent a truly unexpected error; it can represent a problem that you fully anticipate and handle:

function getProfile(email) {
  return getProfileOverNetwork(email)
    .then(null, function (err) {
      //something went wrong getting the profile
      if (err.code === 'NonExistantUser') {
        return defaultUser;
      } else if (profileCached(email)) {
        return getProfileFromCache(email);//fall back to cached profile
      } else {
        throw err;//sometimes we don't have a nice way of handling it
      }
    })
}

拒绝让我们跳过正常的成功行为,直到我们找到一个知道如何处理它的方法.再举一个例子,我们可能有一些深深嵌套在应用程序堆栈底部的函数,它拒绝.这可能直到堆栈的最顶端才能处理,我们可以在那里记录它.关键是拒绝就像同步代码中的异常一样在堆栈中向上移动.

The rejection lets us jump over the normal success behavior until we get to a method that knows how to handle it. As another example, we might have some function that's deeply nested at the bottom of the applications stack, which rejects. This might not be handled until the very top of the stack, where we could log it. The point is that rejections travel up the stack just like exceptions do in synchronous code.

一般来说,只要有可能,如果您正在努力编写一些异步代码,您应该考虑如果这是同步的,我会写什么".从那里到承诺的等价物通常是一个相当简单的转换.

In general, wherever possible, if you are struggling to write some asynchronous code, you should think "what would I write if this were synchronous". It's usually a fairly simple transformation to get from that, to the promised equivalent.

exists 方法中可以使用被拒绝的承诺的一个很好的例子:

A nice example of where rejected promises might be used is in an exists method:

function exists(filePath) {
  return stat(filePath) //where stat gets last updated time etc. of the file
    .then(function () { return true; }, function () { return false; })
}

请注意,在这种情况下,拒绝完全符合预期,仅意味着文件不存在.还要注意它是如何与同步函数并行的:

Notice how in this case, the rejection is totally expected and just means the file does not exist. Notice also how it parallels the synchronous function though:

function existsSync(filePath) {
  try {
    statSync(filePath);
    return true;
  } catch (ex) {
    return false;
  }
}

你的例子

回到你的例子:

如果没有找到用户,我通常会选择拒绝由 findUserByEmail 产生的承诺.这是您完全期望有时会发生的事情,但它是规范的例外,并且可能应该与所有其他错误非常相似地处理.同样,如果我正在编写一个同步函数,我会让它throw 一个异常.

I would normally chose to reject the promise resulting from findUserByEmail if no user was found. It's something you fully expect to happen sometimes, but it's the exception from the norm, and should probably be handled pretty similarly to all other errors. Similarly if I were writing a synchronous function I would have it throw an exception.

有时只返回 null 可能很有用,但这取决于您的应用程序逻辑,可能不是最好的方法.

Sometimes it might be useful to just return null instead, but this would depend on your applications logic and is probably not the best way to go.

这篇关于何时拒绝/解决承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆