繁体   English   中英

节点js:在同一个文件中调用异步function

[英]Node js : Call an async function in the same file

我在一个调用异步 function 的文件中定义了一个 function 以及一个普通的 function。 我以这种方式定义了它们

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;

但它给我一个错误说

类型错误:this.fetchPostData 不是 function

我该如何纠正?

this关键字在这种情况下没有意义。 让我们尝试通过包装 object 名称来重写,如下所示:

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

module.exports = yourObject;

您需要稍微重构一下您的服务。 您可以访问 object 中的 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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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