为什么我们必须在 react-native 的 promise 链的末尾调用 `.done()`? [英] Why do we have to call `.done()` at the end of a promise chain in react-native?

查看:29
本文介绍了为什么我们必须在 react-native 的 promise 链的末尾调用 `.done()`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

react-native 教程 中,它说:

请注意,我们在承诺链的末尾调用 done() - 始终使一定要调用 done() 否则抛出的任何错误都会被吞掉.

Note that we call done() at the end of the promise chain - always make sure to call done() or any errors thrown will get swallowed.

 fetchData: function() {
    fetch(REQUEST_URL)
      .then((response) => response.json())
      .then((responseData) => {
        this.setState({
          movies: responseData.movies,
        });
      })
      .done();
  },

这个空的 .done() 实际上是做什么的?

What does this empty .done() actually do?

推荐答案

我需要澄清的内容:

  • promise 中遇到的异常(在执行 then() 回调期间)存储为 Error 对象,并且不会抛出.
  • Exceptions encountered in promises (during execution of the then() callback) are stored as an Error object, and not thrown.

这种机制意味着您可以推迟操作,而不会有异常在随机时间弄乱您的风险.

This mechanism means that you can defer actions without risk of exceptions inside them messing you up at a random time.

  • done() 不带参数调用 Promise 会查看 Promise 以查看是否有任何存储的异常,并抛出它们.
  • done() called without argument on a promise looks into the promise to see if there are any stored exceptions, and throws them.

这意味着您可以在 Promise 处理期间处理异常,在 Promise 处理结束时.

This means that you can take care of exceptions during promise processing, at the end of the promise processing.

这篇关于为什么我们必须在 react-native 的 promise 链的末尾调用 `.done()`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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