简体   繁体   中英

How to pass function return value to a object in Node.js

I am new to Node.js and I'm developing a REST API for one of my project.

In this case, I have a post request which needs to store some form data to a database. Some values come from form data and some values are generated based on that form values. For example, based on duration value, it needs to calculate final data based on that value. If the duration is 3 months, the final date should change based on the current date. If the duration value is one year, a final date should be changed based on duration with the current date.

I developed a function named releasedfinaldate() to get the date but I cannot pass that function value to the Object. How can I pass that value to Article Object? Please help..

router.post('/', (req, res, next)=>{

const articles = new Articles({

    //articleId: new mongoose.Types.ObjectId(),
    first_name: req.body.first_name,
    last_name: req.body.last_name,
    address: req.body.address,
    id_number: req.body.id_number,
    phone_number: req.body.phone_number,
    amount: req.body.amount,
    weight: req.body.weight,
    duration: req.body.duration,
    addtional_details: req.body.addtional_details,   
    interest_paid: req.body.interest_paid,
    speacial_circumstances: req.body.speacial_circumstances,
    released_date: req.body.released_date,
    released_amount: req.body.released_amount,
    date: moment().format('MMMM Do YYYY, h:mm:ss a'),
    released_final_date: releasedfinaldate(req.body.duration)

});


function releasedfinaldate(duration) {
    const oneyear = moment().add(365, 'days').calendar();
    const threemonths = moment().add(90, 'days').calendar();
    const released_final_date= null;
    if (duration === 1) {
        return oneyear
    } else if (duration === 3) {
        return threemonths
    }  
}
//console.log(releasedfinaldate(3))
articles.save()
.then(result =>{
    console.log(result);
})
.catch(err => console.log(err));
res.status(200).json({
    message:'New Article successfully created.',
    createdArticle: articles
});

});`

Somehow your date function takes some time to return the date value and meanwhile, the next statement should execute. That is a reason your function returns undefined.

Never forgot NodeJS executes the statement asynchronously.

We should use a promise when we need to execute the statement synchronously.

I have tested this snippet in repl.it.

I am not saying I have done my code with the most qualified way but I have given you a solution that you should use this type of similar way for synchronous execution.

You should also async..await in place of promise.

const moment = require('moment');

function generateObject(releasedfinaldate) {
  return new Promise((resolve) => {
    const articles = {
      first_name: "first_name",
      last_name: "last_name",
      address: "address",
      id_number: "id_number",
      phone_number: "phone_number",
      amount: "amount",
      weight: "weight",
      duration: "duration",
      addtional_details: "res",
      interest_paid: "interest_paid",
      speacial_circumstances: "speacial_circumstances",
      released_date: "released_date",
      released_amount: "released_amount",
      date: moment().format('MMMM Do YYYY, h:mm:ss a'),
      released_final_date: releasedfinaldate
    };
    resolve(articles);
  });

}

function releasedfinaldate(duration) {
  return new Promise((resolve) => {
    const oneyear = moment().add(365, 'days').calendar();
    const threemonths = moment().add(90, 'days').calendar();
    const released_final_date = null;
    if (duration === 1) {
      return resolve(oneyear);
    } else if (duration === 3) {
      return resolve(threemonths)
    }
  });
}

releasedfinaldate(3)
  .then((releasedfinaldate) => {
    console.log(releasedfinaldate);
    return generateObject(releasedfinaldate)
  }).then((article) => {
    console.log(article);
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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