Saeesh Tendulkar
Saeesh Tendulkar

Reputation: 703

Node js : Call an async function in the same file

I have a function defined in a file which calls an async function and also a normal function. I have defined them in this way

const cms_service = {
    fetchSinglePost: function(post){
        const image = await cms_service.fetchImageData(post)
        let single_post = {
            post: cms_service.fetchPostData(post),
            image: image
        }
        return single_post
    },
    fetchPostData: function (post) {
        var post_response = {
            id: post.data[0].id
        }
        return post_response
    },
    fetchImageData: async function (post) {
        let storyplay_response = {}
        if(typeof post.data[0].tmc_storyplay[0] !== 'undefined' && post.data[0].tmc_storyplay[0]){
            const storyplay = await axios.get(cms_service_url+"tmc_storyplay/"+post.data[0].tmc_storyplay[0], requestHeader);
            storyplay_response = {
                id: storyplay.data.id
            }
        }
        return storyplay_response
    }
}
module.exports = cms_service;

But it throws me an error saying

TypeError: this.fetchPostData is not a function

How do I correct this?

Upvotes: 1

Views: 836

Answers (2)

Ravi Chaudhary
Ravi Chaudhary

Reputation: 670

You need to refactor your service a bit. You can access object key-values within that object.

const cms_service = () => {
    const fetchSinglePost = function(post){
        const image = await fetchImageData(post)
        let single_post = {
            post: fetchPostData(post),
            image: image
        }
        return single_post
    };

    const fetchPostData = function (post) {
        var post_response = {
            id: post.data[0].id
        }
        return post_response
    };

    const fetchImageData = async function (post) {
        let storyplay_response = {}
        if(typeof post.data[0].tmc_storyplay[0] !== 'undefined' && post.data[0].tmc_storyplay[0]){
            const storyplay = await axios.get(cms_service_url+"tmc_storyplay/"+post.data[0].tmc_storyplay[0], requestHeader);
            storyplay_response = {
                id: storyplay.data.id
            }
        }
        return storyplay_response
    };
}
module.exports = cms_service;

Upvotes: 0

tmhao2005
tmhao2005

Reputation: 17514

this keyword doesn't make sense in this context. Let's try to re-write by wrapping in object name as following:

const yourObj = {
 foo: () => 1,
 bar: () => yourObj.foo(),
}

module.exports = yourObject;

Upvotes: 2

Related Questions