0

I'm using Nodejs and Unirest and have the following code :

import u from 'unirest';
    u.get(firstUrl).query(q).end(function (response) {
                            if (response.status == 200) {
                                posts = response.body;
                                console.log("Step 1");
                            } else {
                                console.log("error");
                            }
                            console.log("Step 2");
                            u.get(secondUrl).query(q).end(function (response) {
                                if (response.status == 200) {
                                   events = response.body;
                                    console.log("Step 3");
                                } else {
                                    console.log("error");
                                }
                            });
                            console.log("Step 4");
                            response.render('myPage', {
                                posts: posts, `
                                events:events
                            });
            });

The first request works very well (posts are sent to the view) but i'm not able to get events from the view. In my terminal, i have :

Step 1
Step 2
Step 4
Step 3

Can you please help me to get both posts and events before rendering "myPage". Thanks for your valuable help.

Maria Minh
  • 1,219
  • 4
  • 15
  • 27

1 Answers1

1

I suggest you to look into promises, you will get a better understanding of the flow.

But like this will work ;)

import u from 'unirest';
u.get(firstUrl).query(q).end(function (response) {
                        if (response.status == 200) {
                            posts = response.body;
                            console.log("Step 1");
                        } else {
                            console.log("error");
                        }
                        console.log("Step 2");
                        u.get(secondUrl).query(q).end(function (response) {
                            if (response.status == 200) {
                               events = response.body;
                                console.log("Step 3");

                            } else {
                                console.log("error");
                            }

                            console.log("Step 4");
                            response.render('myPage', {
                                posts: posts, `
                                events:events
                            });
                        });

        });
DevAlien
  • 2,456
  • 15
  • 17
  • If you want a quick performance boost you could use [async.parallel](https://github.com/caolan/async) to start both requests at the same time and render in that callback. – Cody Gustafson Sep 21 '15 at 00:20