如何防止此代码中的错误“无法破坏未定义或null的字段”:
const [{ field }, { field2 }] = await Promise.all([asynchronous operations...])
答案 0 :(得分: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/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>