Javascript 未处理PromisejectionWarning,但我正在处理错误?
我得到以下错误:Javascript 未处理PromisejectionWarning,但我正在处理错误?,javascript,node.js,reactjs,promise,async-await,Javascript,Node.js,Reactjs,Promise,Async Await,我得到以下错误: Houston we got an err at getGames in index.js (node:72197) UnhandledPromiseRejectionWarning: #<Object> (node:72197) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an as
Houston we got an err at getGames in index.js
(node:72197) UnhandledPromiseRejectionWarning: #<Object>
(node:72197) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:72197) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
error at getGames rp
我每5秒打一次电话
app.get('/api/update', async (req, res) => {
const data = await getGames()
.catch(err => console.log('Houston we got an err at getGames in index.js'))
const dataJson = JSONbig.parse(data);
if (dataJson.game_list && dataJson.game_list.length) {
for (let i = 0; i < dataJson.game_list.length; i++) {
const game = dataJson.game_list[i];
...
在《邮差》中,一个接一个地出现了很多次,但邮差从不出错。所以问题就在我的代码中的某个地方。我已经处理了所有错误,因此我似乎无法找到我没有处理的问题。有几个问题:
- 仅在您可以实际处理错误的位置捕获。在这里,您可能只想在
回调中捕获(否则,如果在.get
中执行getGames
,您将返回已解决的承诺,而不是已拒绝的承诺).catch
- 当发生错误时,不要尝试解析数据(因为它不会被填充)-尝试解析和迭代将导致更多错误
- 没有必要让一个
函数只有一个立即返回的async
wait
感谢您澄清这一点,这确实有助于提高我对错误处理的理解。然而,我很困惑为什么我的getGames函数会出错?我在postman中连续多次手动调用此API,但每次都收到数据。但在我的应用程序中,它是错误的。因为当发生错误时,不要尝试解析数据(因为它不会被填充)-尝试解析和迭代它会导致更多错误-因此,如果没有数据(请确保不要从
.catch
返回任何内容),还请注意,JSON表示法是一种用于以字符串格式表示对象或数组的格式。反序列化后,您只有一个普通对象或数组,而不是JSON-将变量名从dataJson
更改为dataObj
,或者类似的内容可能会有所帮助
app.get('/api/update', async (req, res) => {
const data = await getGames()
.catch(err => console.log('Houston we got an err at getGames in index.js'))
const dataJson = JSONbig.parse(data);
if (dataJson.game_list && dataJson.game_list.length) {
for (let i = 0; i < dataJson.game_list.length; i++) {
const game = dataJson.game_list[i];
...
`https://api.steampowered.com/IDOTA2Match_570/GetTopLiveGame/v1?key=${KEY}&partner=0`
const getGames = () => {
return rp(`https://api.steampowered.com/IDOTA2Match_570/GetTopLiveGame/v1?key=${KEY}&partner=0`);
};
app.get('/api/update', async (req, res) => {
const data = await getGames()
.catch(err => {
console.log('Houston we got an err at getGames in index.js');
// handle error
});
if (!data) {
// There was an error
return;
}
const dataJson = JSONbig.parse(data);
// rest of the code
});