我如何在此代码中防止错误'无法解构'字段'undefined或null':
const [{ field }, { field2 }] = await Promise.all([asynchronous operations...])
这是使用第三方库(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>