如何在JS中防止错误'无法解构......'

问题描述 投票:1回答:1

我如何在此代码中防止错误'无法解构'字段'undefined或null':

const [{ field }, { field2 }] = await Promise.all([asynchronous operations...])
javascript arrays ecmascript-6 es6-promise
1个回答
0
投票

这是使用第三方库(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/[email protected]/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/[email protected]/index.js"></script>
© www.soinside.com 2019 - 2024. All rights reserved.