Return 承诺 node.js

Return promise in node.js

我尝试从 API 中 return node.js 中的数据,但我遇到了问题,因为我需要一个异步函数,我无法确定正确使用我保证,我已经尝试了所有方法,但我无法将结果放在 return 中,只能放在 console.log 中,有人帮助我吗?

const express = require('express')
const MFA = require('mangadex-full-api')

module.exports = {
    async indexManga(req, res) {
         
        const mangalist = MFA.login('DarksGol', 'R@ul1605', './md_cache/').then(async () => {

            manga = []
                await MFA.Manga.search('Kiss').then(results => {
                results.forEach((elem, i) => {   
                    let obj = {}
                    obj.status = elem.status
                    obj.title = elem.title
                    
                    manga.push(obj)
                })
            }).catch(console.error)

            return manga

        }).catch(console.error) 

        console.log(await mangalist)
        return mangalist
    }
}

没有发生错误,只是根据请求无限加载

const express = require('express')
const routes = express.Router()

const searchManga = require('../src/controllers/searchManga')

routes.get('/searchManga', searchManga.indexManga)

module.exports = routes

我不明白为什么这会导致“根据请求无限加载”,但您可以将代码大大简化为

const express = require('express');
const MFA = require('mangadex-full-api');

module.exports = {
    async indexManga(req, res) {
        await MFA.login('DarksGol', 'R@ul1605', './md_cache/')
        const mangaList = [];
        const results = await MFA.Manga.search('Kiss');
        results.forEach(elem => {   
            mangaList.push({
                status: elem.status,
                title: elem.title,
            });
        });
        return mangalist;
    },
};

看起来 indexManga 是一个端点。每个端点函数必须通过发送响应(res.send()、res.json()、res.end() 等)来结束请求-响应周期。如果 indexManga 是端点,解决方案将是:

...

//return mangalist
res.send(mangalist)

//return mangalist
res.json({ status: "success", message: "logged in successfully" })

如果是中间件:

async indexManga(req, res, next) {
  ...
  //return mangalist
  return next()
}

编辑:您在某些地方不正确地使用 async/await.then()。 试试这个方法:

module.exports = {
    indexManga(req, res) {
        MFA.login('DarksGol', 'R@ul1605', './md_cache/').then(() => {

            manga = []
            MFA.Manga.search('Kiss').then(results => {
                results.forEach((elem, i) => {   
                    let obj = {}
                    obj.status = elem.status
                    obj.title = elem.title
                    
                    manga.push(obj)
                })
                
                res.json({ status: "success", data: manga })
                
            }).catch((err) => {
               res.json({ status: "fail", error: err })
            })
            

        }).catch((err) => {
           res.json({ status: "fail", error: err })
        })
    }
}