[英]NodeJS: make less requests by API
I am trying to process response data and do not make next request before current data didn't processed.我正在尝试处理响应数据,并且在当前数据未处理之前不发出下一个请求。 I tried use async/await and generators.我尝试使用 async/await 和生成器。
Generator:发电机:
private *readData() {
const currentUrl = this.getUrl();
const requestSettings = this.getRequestSettings();
yield axios.get( currentUrl, requestSettings).then( (response: any) => {
console.log('Make request');
return this.getData(response);
});
}
*readItem() {
let responseData: any;
if (!responseData) {
const response = this.readData();
responseData = response.next();
}
console.log('res data:', responseData['value']);
yield responseData['value'].then((res: any) => {
return res;
});
}
and then in the main code I do next:然后在我接下来的主代码中:
for (let i=0;i<10;i++) {
item = transport.readItem().next();
console.log("R:", item);
}
Another idea was using async/await另一个想法是使用 async/await
async readItems() {
const headers = this.settings.headers;
const response = await axios.get( url, {
headers: headers
});
return response.data;
}
But in this case I get a promise in the response, if I just try to call this method 10 times.但是在这种情况下,如果我尝试调用此方法 10 次,我会在响应中得到 promise。
I read 10 items, but I still make 10 requests to the server.我阅读了 10 个项目,但我仍然向服务器发出 10 个请求。 Is it possible make one request, processed 10 items, and then make the second request?是否可以提出一个请求,处理 10 个项目,然后提出第二个请求? Maybe I have to use another pattern or whatever.也许我必须使用另一种模式或其他方式。
Async/await is right approach, just put await
in front of readItem()
and the Promise
you get will be await
ed that will give you desired. Async/await 是正确的方法,只需将await
放在readItem()
前面,您获得的Promise
将被await
,这将满足您的需求。 If your loop is in top level use readItem().then()
.如果您的循环处于顶层,请使用readItem().then()
。 The latest NodeJS version allows await
in top level.最新的 NodeJS 版本允许在顶层await
。
for (let i=0;i<10;i++) {
item = await transport.readItem();
console.log("R:", item);
}
I found next solution我找到了下一个解决方案
(async () => {
for (let i = 0; i < 10; i++) {
item = await transport.readItem();
console.log("R:", item);
}
})();
because I ran this part of code inside script without any functions/methods因为我在脚本中运行了这部分代码,没有任何功能/方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.