Home > Software design >  receivedImageUrl variable not updating
receivedImageUrl variable not updating

Time:11-06

const express = require('express');
const https = require("https");


const app = express();

app.use(express.json())
app.use("/public", express.static("public"));
app.set('view engine', 'ejs');

const API_ID = "2d8f8b46"; 
const API_KEY = "b5251cc3bd3b7c030fc4a629c5e8aba0"  ; 



app.get('/', (req, res) => {
    const url = "https://api.edamam.com/api/recipes/v2?type=public&q=pizza&app_id=" API_ID "&app_key=" API_KEY ;
    

    var receivedImageUrl = " " ;
    https.get(url , function(response){
      
      
      console.log(response.statusCode);
      let wdata = '';
      response.on("data" , function(data){
          wdata  = data ;
          
          
      });
          response.on("end" , function(){
          recipeData = JSON.parse(wdata);
          
          receivedImageUrl = recipeData.hits[0].recipe.image; 
          
            
      });
      
    });
    console.log(receivedImageUrl);
    res.render("home" , {
      imageUrl : receivedImageUrl 
      
    });
    // console.log(receivedImageUrl);
    
    
  });
  app.set('port', process.env.PORT || 3000);
  
app.listen("3000",()=>{
  console.log("app is running")
});

enter image description here Value of receivedImageUrl variable not updating

I am trying to use the image url from that i receive from the api to render it using EJS . The receivedImageUrl variable that is inside the "response.on" function is not updating its value to the declaration hence the value of receivedImageUrl variable remains empty string . Please help tresolve the issue

CodePudding user response:

As you know javascript and nodejs are asynchronous and non-blocking by default. That means when it finds some async function or IO operation, that will be put into event loop and continue the program flow. In your case, HTTP call is a non-blocking IO operation so it will put this operation and then continue the flow. when the data is available, the 'data' and 'end' events will be created and after that the logic inside response.on() callbacks will be executed.

so your res.render() function will be called before 'data' and 'end' events are thrown. so you should put this res.render() method inside the 'end' event callback

  • Related