简体   繁体   English

如何在 Node.js 中进一步执行我们的代码之前等待 HTTP 请求

[英]How to wait for an HTTP Request before executing our code further in Node.js

I am trying to make a GET Request to an API and want to store the data it returns in another variable but Javascript doesn't wait for the request to be complete and log my variable as Undefined我正在尝试向 API 发出 GET 请求,并希望将它返回的数据存储在另一个变量中,但 Javascript 不会等待请求完成并将我的变量记录为 Undefined

app.get("/", function (req, res) {
    const url = "https://animechan.vercel.app/api/random";
    let str = "";
    let quote;
    
    https.get(url,(resposne)=>{
        resposne.on("data",(data)=>{
            str+=data;
        });
        resposne.on("end",()=>{
            const info=JSON.parse(str);
            quote=info.quote;
        });
    });

    console.log(quote);
    res.render("header", {
        quote: quote
    });
});

I would be glad if someone can tell me how to solve this problem and where can I study about it more as I am a beginner to javascript.如果有人能告诉我如何解决这个问题,我会很高兴,因为我是 javascript 的初学者,我在哪里可以更多地研究它。

Quick answer is that you need to put that code inside of response.on('end') callback.快速回答是您需要将该代码放在response.on('end')回调中。

resposne.on("end",()=>{
   const info=JSON.parse(str);
   quote=info.quote;
   // now we can use res.render
   console.log(quote);
   res.render("header", {
      quote: quote
   });
});

However, following such approach will lead to a callback hell , unreadable and unextendable code of your project.但是,遵循这种方法将导致项目的回调地狱、不可读和不可扩展的代码。 Ideally, you should start using promises .理想情况下,您应该开始使用promises Promises are an essential part of javascript and are a must have knowledge for a developer. Promises 是 javascript 的重要组成部分,是开发人员必须具备的知识。

Also, I'd like to note that you don't need to implement http calls functionality from scratch or try to wrap such code into promise.另外,我想指出您不需要从头开始实现 http 调用功能或尝试将此类代码包装到 promise 中。 Instead, it is better to use fetch api (if you are using node version 18 or above) or use corresponding libraries, for example, node-fetch .相反,最好使用fetch api(如果您使用的是 node 版本 18 或更高版本)或使用相应的库,例如node-fetch

All you have to do here is call res.send after the HTTP call is complete您在这里要做的就是在 HTTP 调用完成调用 res.send

app.get("/", function (req, res) {
    const url = "https://animechan.vercel.app/api/random";
    let str = "";
    let quote;
    
    https.get(url,(resposne)=>{
        resposne.on("data",(data)=>{
            str+=data;
        });
        resposne.on("end",()=>{
            const info=JSON.parse(str);
            quote=info.quote;

            // Send response _after_ the http call is complete
            console.log(quote);
            res.render("header", {
                quote: quote
            });
        });
    });
});

I would suggest using node's fetch, since the default HTTP client is a bit less ergonomic我建议使用节点的获取,因为默认的 HTTP 客户端不太符合人体工程学

Fetch API reference: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API获取 API 参考: https ://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

Node.js API reference: https://nodejs.org/dist/latest-v18.x/docs/api/globals.html#fetch Node.js API 参考: https ://nodejs.org/dist/latest-v18.x/docs/api/globals.html#fetch

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM