我有一个生成器,用于更新对象。在这里,我需要调用多个返回promise的函数,所以我使用yield all和(明确的双关语(all is good。类似这样的东西:
function* updateTheThing() {
...
const [resultA, resultB, resultC] = yield all([funcA(), funcB(), funcC()]);
...
}
这适用于更新单个项目,但我想更新一个项目数组。我的想法是在物品上使用地图和地图,但问题是我不能在地图内屈服。我以前也做过类似的事情,当时我所需要做的就是调用一些API,如下所示:
const promises = things.map(thing => {
return call(api.someEndpoint);
});
const data = yield all(promises);
但我不能在这里这样做,因为我没有使用redux传奇的呼吁。我现在的代码是这样的,但它不起作用:
function* updateAllTheThings() {
try {
const updatedThings = things.map(thing => {
const resultA = funcA(); // resultA is a promise
const resultB = funcB(); // resultB is a promise
const resultC = funcC(); // resutlC is a promise
});
} catch (error) {
console.log(`error updating all the things: ${error}`);
}
}
resultA、resultB和resultC是promise,但我需要解析的值,因为我需要在map语句中进一步使用它。
也许我的做法是错误的,但我被难住了。有人有什么建议吗?
好吧,在Nicolas Tower对这个问题的回答的帮助下,我能够重新思考并重新编写我的代码,以按预期工作。我会在这里添加我的解决方案,以防有人觉得它有用。
因此,我决定使用的部分问题是,用他们的话来说,创建一个迷你传奇,所以我的代码现在是这样的:
function* updateAllTheThings() {
try {
const promisedThings = things.map(thing => {
return call (function* () {
const resultA = funcA(); // resultA is a promise
const resultB = funcB(); // resultB is a promise
const resultC = funcC(); // resutlC is a promise
});
});
const updatedThings = yield all(promisedThings);
...
} catch (error) {
console.log(`error updating all the things: ${error}`);
}
}