【发布时间】:2021-10-09 22:54:40
【问题描述】:
我正在尝试使用 node-fetch 从 Google API 获取 JSON 输出。我成功地记录了它,但是当我尝试将它分配给一个变量时,我得到了一个错误。
我的代码:
client.on("ready", () => {
fetch(url)
.then((res) => res.json())
.then((data) => console.log(JSON.stringify(data, null, 2)));
console.log("##########################################################################");
search1 = JSON.stringify(data, null, 2);
console.log(search1);
});
错误:
UnhandledPromiseRejectionWarning: ReferenceError: data is not defined
at Client.<anonymous> (C:\Users\kalat\Documents\discord_code\src\main.js:15:28)
at Client.emit (events.js:375:28)
at WebSocketManager.triggerClientReady (C:\Users\kalat\Documents\discord_code\node_modules\discord.js\src\client\websocket\WebSocketManager.js:431:17)
at WebSocketManager.checkShardsReady (C:\Users\kalat\Documents\discord_code\node_modules\discord.js\src\client\websocket\WebSocketManager.js:415:10)
at WebSocketShard.<anonymous> (C:\Users\kalat\Documents\discord_code\node_modules\discord.js\src\client\websocket\WebSocketManager.js:197:14)
at WebSocketShard.emit (events.js:375:28)
at WebSocketShard.checkReady (C:\Users\kalat\Documents\discord_code\node_modules\discord.js\src\client\websocket\WebSocketShard.js:475:12)
at WebSocketShard.onPacket (C:\Users\kalat\Documents\discord_code\node_modules\discord.js\src\client\websocket\WebSocketShard.js:447:16)
at WebSocketShard.onMessage (C:\Users\kalat\Documents\discord_code\node_modules\discord.js\src\client\websocket\WebSocketShard.js:301:10)
at WebSocket.onMessage (C:\Users\kalat\Documents\discord_code\node_modules\ws\lib\event-target.js:132:16)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:14484) 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(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:14484) [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.
我确实从.then((data) => console.log(JSON.stringify(data, null, 2))); 获得了 JSON 输出。
【问题讨论】:
-
data是第二个.then()函数的本地函数。你不能在函数之外引用它。
标签: javascript node.js promise es6-promise