简体   繁体   中英

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?

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;

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;

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