我正在尝试使用ES6 AsyncGenerator函数从分页API中检索我的ReactNative应用程序中的数据,但没有成功。我正在重用我能够在web应用程序中成功使用的代码,这些代码也使用了ES6和React。我相当确定这将归结为某种配置问题,或语言支持,但我不知道我的问题是什么,因为错误不是特别有帮助。如果必须这样做,我显然可以避免使用AsyncGenerator,并以另一种方式实现它。
基本的生成器函数具有以下结构:
export async function* apiPager() {
let nextToken = null;
do {
const resp = await makeAPICall(nextToken);
nextToken = resp.nextToken;
yield resp;
} while(nextToken)
}我用来处理生成器的代码如下:
const pager = apiPager(...)
console.log('pager', pager);
for await (const resp of pager) {
doThings(resp);
}当我尝试使用此代码时,我在控制台中看到以下内容:
pager AsyncIterator {_invoke: ƒ}_invoke: ƒ enqueue(method, arg)arguments: (...)caller: (...)length: 2name: "enqueue"prototype: {constructor: ƒ}__proto__: ƒ ()[[FunctionLocation]]: runtime.js:167[[Scopes]]: Scopes[3]__proto__: next: ƒ (arg)return: ƒ (arg)throw: ƒ (arg)Symbol(Symbol.asyncIterator): ƒ ()constructor: ƒ AsyncIterator(generator)__proto__: Object
YellowBox.js:71 Possible Unhandled Promise Rejection (id: 0):
TypeError: _iterator[(intermediate value)(intermediate value)(intermediate value)] is not a function
TypeError: _iterator[(intermediate value)(intermediate value)(intermediate value)] is not a function
at WorkoutHistory.fetchSets$ (blob:http://localhost:8081/8ee39d52-49af-4c3e-a8a7-b3d585ce1223:163566:234)
at tryCatch (blob:http://localhost:8081/8ee39d52-49af-4c3e-a8a7-b3d585ce1223:23518:19)
at Generator.invoke [as _invoke] (blob:http://localhost:8081/8ee39d52-49af-4c3e-a8a7-b3d585ce1223:23693:24)
at Generator.prototype.<computed> [as next] (blob:http://localhost:8081/8ee39d52-49af-4c3e-a8a7-b3d585ce1223:23561:23)
at tryCatch (blob:http://localhost:8081/8ee39d52-49af-4c3e-a8a7-b3d585ce1223:23518:19)
at invoke (blob:http://localhost:8081/8ee39d52-49af-4c3e-a8a7-b3d585ce1223:23594:22)
at blob:http://localhost:8081/8ee39d52-49af-4c3e-a8a7-b3d585ce1223:23624:13
at tryCallTwo (blob:http://localhost:8081/8ee39d52-49af-4c3e-a8a7-b3d585ce1223:24829:7)
at doResolve (blob:http://localhost:8081/8ee39d52-49af-4c3e-a8a7-b3d585ce1223:24993:15)
at new Promise (blob:http://localhost:8081/8ee39d52-49af-4c3e-a8a7-b3d585ce1223:24852:5)
[![error messages][1]][1]第一个问题似乎非常明显,那就是pager的类型是AsyncIterator,而不是我在web应用程序中看到的AsyncGenerator类型。但据我所知,其中任何一个都应该可以与for await (...)循环一起操作,不是吗?一些奇特的事情正在发生。如果可以的话请告诉我。
发布于 2020-04-19 22:18:57
好吧..。我从来没有得到过答案。我还发布了这个问题:https://github.com/facebook/react-native/issues/27432,但没有得到任何支持。
我确实找到了一个解决方法,我将在这里重新发布,只是稍微不太令人满意:
解决方法(来自github问题)
async function* asyncGen() {
yield 'whatever';
}
const gen = asyncGen();
while (!gen.done)
console.log('result', (await gen.next()).value);我想这只是一点小麻烦,因为for await (... of ...)的语法改进没有编写生成器函数的能力有价值,而不是创建迭代器的能力。然而,如果能理解这里的问题所在,那将是一件很好的事情。
https://stackoverflow.com/questions/59185977
复制相似问题