Ham*_*deh 3 javascript promise typescript angular
我想在打字稿代码中获取 Promise allSettled 结果的值。在 JavaScript 中这工作得很好。
Promise.allSettled([
Promise.resolve(33),
new Promise(resolve => setTimeout(() => resolve(1000), 0)),
25000,
Promise.reject(new Error('failed!'))
])
.then(values => {
let allValues = values.filter(c=>c.status === 'fulfilled').map(v=>v.value);
console.log(allValues);
});Run Code Online (Sandbox Code Playgroud)
但在打字稿中我找不到正确的语法。该项目只有状态,没有价值属性。我使用的是最新版本的 typescript 3.9.7
好吧,我终于找到了在打字稿中使用 Promise.allSettled 的正确语法:
更新:感谢@myol,我更新了代码,没有不必要的地图:
const dummyResolve1 = Promise.resolve(1000);
const dummyResolve2 = new Promise(resolve => setTimeout(() => resolve(2000), 0));
const dummyError = Promise.reject(new Error('failed'));
const dummyPromises = [dummyResolve1, dummyResolve1, dummyError];
Promise.allSettled(dummyPromises)
.then(results => {
const allValues = (results.filter(c=>c.status === 'fulfilled') as PromiseFulfilledResult<any>[])
.map(c=>c.value);
console.log(allValues);
const failedResults =
(results.filter(c=>c.status === 'rejected') as PromiseRejectedResult[])
.map(c=>c.reason);
console.log(failedResults);
});
Run Code Online (Sandbox Code Playgroud)
旧代码:
Promise.allSettled([
Promise.resolve(1000),
new Promise(resolve => setTimeout(() => resolve(2000), 0)),
1500,
Promise.reject(new Error('failed'))
])
.then(values => {
let allValues = values.filter(c=>c.status === 'fulfilled').map(c=> <PromiseFulfilledResult<any>>c).map(c=>c.value);
console.log(allValues);
let failedResults = values.filter(c=>c.status === 'rejected').map(c=> <PromiseRejectedResult>c).map(c=>c.reason);
console.log(failedResults);
});
Run Code Online (Sandbox Code Playgroud)