weeraa
weeraa

Reputation: 1195

stop execution till response come back in node js

I'm a beginner to node js and sequelize ORM.

Below is my code and it has while loop.

        var arr = [];
        var orgParntId = 7;

        do {
            console.log('LOG 1');
            global.meal.findOne({
                where: {
                    id: orgParntId,
                },
            }).then(meal => {
                orgParntId = meal.parentId;
                arr.push(meal.parentId);
                console.log('LOG 2');
            });
            console.log('LOG 3');
        }
        while (orgParntId < 0);
        console.log('LOG 4');

There is a parent child relation table and when I give child element Id, It should loop and find all related item Id hierarchic. The problem is, the query run at last. I've added logs and after execute the function, it is shown the log like below.

LOG 1
LOG 3
LOG 4
LOG 2

It is execute the query at last. What I need is, to execute above loop like

LOG 1
LOG 2
LOG 3
LOG 1
LOG 2
LOG 3
.
.
.
LOG 4

What is the approach of wait till execute the sequelize ORM query and then execute next line?

Upvotes: 0

Views: 474

Answers (2)

Aᴍɪʀ
Aᴍɪʀ

Reputation: 7803

This is one of the examples that async and await shine in!

const main = async function () {
    var arr = [];
    var orgParntId = 7;

    do {
        const meal = await global.meal.findOne({
            where: {
                id: orgParntId,
            },
        })
        orgParntId = meal.parentId;
        arr.push(meal.parentId);
    } while (orgParntId < 0); // are you sure this shouldn't be ">"?
    return arr;
}

main().then(array => {
    console.log(array);
});

The nature of those queries are asynchronous, and what you want to do is to iterate over your data and query their parent one by one. Using async/await you can write your code in a sequential/synchronous way and wrap them in an async function.

I'd recommend the link that @typ has posted if you want to know about how JS handles async functions.

Upvotes: 1

tyb
tyb

Reputation: 201

global.meal.findOne() operation is an asynchronous operation. .then(meal) will not be executed just after you call .findOne() but at a later time (when the data is ready). So you need to handle it not with a do-while loop but in a different way.

For starters you must understand asynchrony in Javascript. Have a look at these:

Getting to know asynchronous JavaScript: Callbacks, Promises and Async/Await Understanding JavaScript Promises, Pt. I: Background & Basics

Upvotes: 0

Related Questions