Node.js 将在外部执行代码,而不是等待请求解析(从您的 API 获取数据),它不会打印任何内容,因为在执行时仍然没有任何内容,并且只有在节点从您的 api(这将需要几毫秒)将执行请求中的代码。这是因为 nodejs 是异步和非阻塞语言,这意味着它不会阻塞或停止代码,直到您的 api 返回数据,它会继续运行并在收到响应后完成。
在回调函数中完成所有你想要的数据操作是一个很好的做法,不幸的是你不能依赖你拥有的结构。
这是您的代码示例,只是注释掉了操作顺序:
let data_json = ''; // global variable
app.get('/', (req, res) => {
//NodeJS STARTS executing this code
request('http://my-api.com/data-export.json', (error, response, body) => {
//NodeJS executes this code last, after the data is loaded from the server
data_json = JSON.parse(body);
console.log( data_json );
//You should do all of your data_json manipluation here
//Eg saving stuff to the database, processing data, just usual logic ya know
});
//NodeJS executes this code 2nd, before your server responds with data
//Because it doesn't want to block the entire code until it gets a response
console.log(data_json, 'Data Test - outside request code');
})
假设您想使用第一个请求中的数据发出另一个请求 - 您必须执行以下操作:
request('https://your-api.com/export-data.json', (err, res, body) => {
request('https://your-api.com/2nd-endpoint.json', (err, res, body) => {
//Process data and repeat
})
})
如您所见,这种模式很快就会变得非常混乱——这被称为回调地狱,所以为了避免大量嵌套请求,有一种语法糖可以使这段代码看起来更加花哨和可维护,它被称为异步/等待模式。以下是它的工作原理:
let data_json = ''
app.get('/', async (req,res) => {
try{
let response = await request('https://your-api.com/endpoint')
data_json = response.body
} catch(error) {
//Handle error how you see fit
}
console.log(data_json) //It will work
})
此代码与您拥有的代码执行相同的操作,但不同之处在于您可以一个接一个地创建任意数量的await request(...),并且没有嵌套。
唯一的区别是你必须声明你的函数是异步的 async (req, res) => {...} 并且所有的 let var = await request(...) 都需要嵌套在 try-catch 块中。这样你就可以发现你的错误。如果您认为有必要,您可以将所有请求放在 catch 块中。
希望这会有所帮助:)