-1

In my methods.JS file there have a function called addNedData() here payload is giving proper output after creating the data.

methods.addNewData = (req, res, modelName, body ) =>{
    modelName.create({
        id: body.id,
        title : body.title,
    }).then((payload) => {
        payload.success = true
        return payload
    }).catch(err => {
        err.success = false
        return err
    })
}

from my controller file I am calling the function like this. the function is being called and executing also but in response value it is not returning any data..

exports.createCampaign = async (req, res) => {
    let body = req.body
    let response= await Methods.addNewData(req, res, Campaign, body)
    console.log(response)
}

error is response is undefine..

Rabbani_
  • 450
  • 1
  • 10
  • 30
  • You don't return the promise from the method. Also why do you pass req and res to it? They aren't used, and it means that your business logic has access to the transport layer, defying the whole point of layering the app. – jonrsharpe Feb 03 '20 at 08:03
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Shihab Feb 03 '20 at 08:04
  • Instead of using function you can use promise for resolve or reject your output from addNewData – Prakash Karena Feb 03 '20 at 08:04
  • I have updated my question.. actually I am returning my payload .. BUT why down Vote – Rabbani_ Feb 03 '20 at 08:04

1 Answers1

0

Your addNewData needs to return the promise.

methods.addNewData = (req, res, modelName, body ) =>{
    return modelName.create({
        id: body.id,
        title : body.title,
        campaign_place: body.campaign_place,
        campaign_bp: body.campaign_bp,
        Campaign_manager: body.Campaign_manager,
        campaign_duration: body.campaign_duration,
        created_by: body.created_by
    }).then((payload) => {
        payload.success = true
        return payload
    }).catch(err => {
        err.success = false
        return err
    })
}

Notice the return keyword on line 2.

C.OG
  • 6,236
  • 3
  • 20
  • 38