的NodeJS:如何使用异步/ AWAIT来处理HTTP请求油门的错误?
我米试图建立一个搜索API这需要的位置作为参数,并返回该位置的经度和纬度。我米使用。例如:/?locate=Warsaw,Poland&json=1这将返回该位置所需要的经度和纬度。
这是代码片段我有:
const url = '/?locate=Warsaw,Poland&json=1';
const getData = async url => {
try {
const response = await fetch(url);
const json = await response.json();
console.log(json);
} catch (error) {
console.log(error);
}
};
getData(url);
有了这个,这是我看到的错误:
node geocode.js
{success: false, error: { code: '006', message: 'Request Throttled.'}}
我猜的错误是因为我需要节流被击中API 。我不知道如何使用率限制器异步/等待。任何帮助,将不胜感激。
编辑:基于下面的答案,我仍然看到“请求经过调节”
var request = require('request');
const fetch = require("node-fetch");
const requester = {
lastRequest: new Date(),
makeRequest: async function(url) {
// first check when last request was made
var timeSinceLast = (new Date()).getTime() - this.lastRequest.getTime();
if (timeSinceLast < 2000) {
this.lastRequest = new Date(this.lastRequest.getTime() + (2000 - timeSinceLast));
await new Promise(resolve => setTimeout(resolve, 2000-timeSinceLast));
// await new Promise(resolve => setTimeout(resolve, timeSinceLast));
}
const response = await fetch(url);
const json = await response.json();
return json;
}
};
requester.makeRequest('/?locate=Warsaw,Poland&json=1')
.then(console.log)
我还在原地得到同样的错误:
{ success: false, error: { code: '006', message: 'Request Throttled.' } }
这是因为geocode pricing的?有什么办法来限制从用户端请求的速度?
回答如下:也许你认为是用于发送所有请求了一个对象,该对象可以跟踪最后一次有人要求时的感觉。例如
const requester = {
lastRequest: new Date(2000,0,1),
makeRequest: async function (url) {
// first check when last request was made
var timeSinceLast = (new Date()).getTime() - this.lastRequest.getTime();
this.lastRequest = new Date();
if (timeSinceLast < 1000) {
this.lastRequest = new Date(this.lastRequest.getTime() + (1000 - timeSinceLast));
await new Promise(resolve => setTimeout(resolve, 1000-timeSinceLast));
}
// make request here and return result
const response = await fetch(url);
const json = await response.json();
return json;
}
};
https://jsfiddle/3k7b0grd/
如果你使用requester.request
,它只是让你做一个请求,每秒一次,并等待足够长的时间(甚至连续请求)服从这个速度极限