函数返回未定义的承诺

时间:2020-07-29 09:07:11

标签: javascript node.js express

我使用node.js和Express设置了服务器,并且正在使用此功能从API获取网站的主要类别。

function getMainCategories() {
    got(`${base_url}/categories/parent/root`, { searchParams: { secretKey: `${secretKey}` } })
        .then(response => {

            // main categories
            let mains = JSON.parse(response.body);
            console.log(mains); // works
            return mains;
        })
        .catch(error => {
            console.log(error.response.body);
            res.status(404).end();
        });
    }

在该函数内部,一切正常。但是,例如,当我在其他地方使用getMainCategories()渲染页面并将其登录到该函数时,它显示为未定义。

router.get('/categories', function (req, res, next) {

    const mains = getMainCategories();
    console.log(mains); // undefined

    // some code
});

当我尝试在其中登录以下内容时,它就是它记录的内容:

console.log(JSON.parse(response.body)); // Promise { undefined }

在此之前,我在第二个功能中手动发出了请求,并且它起作用了。为什么它只能在.then()内部使用,又如何在其余代码中使用它?

0 个答案:

没有答案