【问题标题】:How to prevent error 'Cannot destructuring...' in JS?如何防止 JS 中出现“无法解构...”错误?
【发布时间】:2019-07-23 23:21:41
【问题描述】:

如何防止在此代码中出现错误“无法解构未定义或 null 的“字段”:

const [{ field }, { field2 }] = await Promise.all([asynchronous operations...])

【问题讨论】:

  • 通过确保承诺解析为具有这些属性的对象?即第一个应该有field 作为属性,第二个应该有field2。在您的情况下,其中一个承诺以undefinednull 解决。防止这种情况发生。
  • @trincot in Promise.all 我使用 DB 执行操作,在一种情况下,promise 返回具有此属性的对象,而在另一种情况下,它返回“null”。如果 promise 返回“未定义”,那么我可以使用默认值,但不能将其与“空”值一起使用。
  • 那么当相应的 Promise 解析为 undefinednull 时,您希望变量 field (field2) 发生什么?
  • 您可以使用 Array#map E.G. 将 null 映射到 undefined (await Promise.all([...])).map( x => x === null ? undefined : x ) 然后使用默认值。
  • @Paulpro,这将是我逃避的答案的香草 JS 版本。您应该将其发布为答案。 :)

标签: javascript arrays ecmascript-6 es6-promise


【解决方案1】:

这是使用 3rd 方库 (async-af) 的一种可能解决方案。

const input = [Promise.resolve(null), Promise.resolve({field2: 'b'})];

(async () => {
  const [{field}, {field2}] = await AsyncAF(input).map(
    result => result != null ? result : {field: null, field2: null}
  );
  console.log(field, field2);
})();
<script src="https://unpkg.com/async-af@7.0.10/index.js"></script>

或者,如果您想要使用默认值:

const input = [Promise.resolve(null), Promise.resolve({field2: 'b'})];

(async () => {
  const [{field = 'defaultValue'}, {field2 = 'defaultValue'}] = await AsyncAF(input)
    .map(result => result != null ? result : {});
  console.log(field, field2);
})();
<script src="https://unpkg.com/async-af@7.0.10/index.js"></script>

【讨论】:

  • 糟糕,刚刚意识到这不会涵盖第二个结果为空。将不得不看更长的时间。编辑:好的,已修复。
猜你喜欢
  • 1970-01-01
  • 2015-07-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-02
  • 1970-01-01
  • 2018-12-16
  • 2013-06-07
  • 1970-01-01
相关资源
最近更新 更多