1

I'm working to developed API with NodeJS. I got undefined value when I print the value.

Here's my code:

const modelMateris = require("../models/materi");

var Home = {
  getHome: (req, res, next) => {

    const materisAsync = new Promise((resolve, reject) => {
      modelMateris.find({},(err, res) => {
        if(err) reject(err);
        resolve(res);
      });
    });

    var a = materisAsync
      .then(res => console.log(res))
      .catch(res => console.log(err));

    res.send({code:1000, materis:a });
  }
}

module.exports = Home;

I just want to show the output of var A into RESTAPI. So how to print it in NodeJS?

1 Answer 1

1
materisAsync
    .then(res => {
        console.log(res)
        const a = res
        res.send({code:1000, materis: res});
    })
    .catch(res => console.log(err));

As you are using then block the promise resolved value will be coming in the then block and be assigned to a variable, you can use async await in place of then block, as shown below.

var Home = {
        getHome: async (req, res, next) => {
            try {
                const materisAsync = new Promise((resolve, reject) => {
                    modelMateris.find({}, (err, res) => {
                        if (err) reject(err);
                        resolve(res);
                    });
                });

                const a = await materisAsync
                const b = await secondApicall // like this you can call multiple api

                res.send({ code: 1000, materis: a});
            } catch(error) {
                console.log(error)
            }
        }
    }
Sign up to request clarification or add additional context in comments.

2 Comments

actually i want to create multiple API coming from different db model. so i declare variable to handle it. btw ur code still not working cause i run it with postman
For calling multiple api you can use async await, i have edited the code, please find the same.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.