Search code examples
javascriptnode.jspromisereturn

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

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

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

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

module.exports = routes

Solution

  • 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()
    }
    

    EDIT: you are using async/await with .then() improperly in some places. Try this way:

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