简体   繁体   中英

Return promise in node.js

i try to return data in node.js from a APIs , but I'm having problems, because I need an asynchronous function, I couldn't understand for sure the correct use of the promise, I've tried everything and I couldn't put the result in the return, only in the console.log, somebody help me?

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
    }
}

no error occurred, only infinite loading on request

I don't see why this would cause " infinite loading on request ", but you could greatly simplify the code to just

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;
    },
};

Looks like indexManga is an endpoint. Each endpoint function must end the request-response cycle by sending a response ( res.send(), res.json(), res.end(), etc). If indexManga s an endpoint, the solution would be:

...

//return mangalist
res.send(mangalist)

or

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

If it is a meddleware:

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

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