我的诺言有一个具体问题-我没有找到解决问题的办法。
例如,我有服务(类)列表
const services = [
FirstCacheDataProvider,
SecondCacheDataProvider,
// etc, there can be more services, unspecified number of services
];
每个类都实现返回promise的方法(例如find)(它在该方法内部解析,并且我无法访问此方法的主体。它显然是异步的)
现在,我要一个接一个地调用此方法,直到返回不清空结果。
没有那么大的链,有没有办法做到这一点?
工作流程示例:
我们有4个服务
FirstCacheDataProvider.find() // result of promise is empty
SecondCacheDataProvider.find() // result of promise is empty
ThirdCacheDataProvider.find() // result of promise IS NOT EMPTY
// fourth service's method is not called
答案 0 :(得分:6)
一种简单的方法是使用for
循环和await
函数中的每个服务调用async
:
for (let i = 0; i < services.length; i++) {
const result = await services[i].find();
if (result === 'NOT EMPTY') { // or whatever condition you're searching for.. .length?
break;
}
}
答案 1 :(得分:1)
类似的事情应该可以解决。我以不要空来假设您的意思不是undefined
:)
const services = [
FirstCacheDataProvider,
SecondCacheDataProvider,
// etc, there can be more services, unspecified number of services
]
// reduce all services to a promise that either returns first value or calls next service.find
services.reduce(
(pending, service) => pending.then(value => value !== undefined ? value : service.find()),
Promise.resolve()
).then(firstNonEmptyResult => console.log(firstNonEmptyResult))