Home > Software design >  Attempting to retrieve JSON data results in [ Promise { <pending> }, Promise { <pending>
Attempting to retrieve JSON data results in [ Promise { <pending> }, Promise { <pending>

Time:03-20

I am attempting to retrieve the JSON data stored in the following API:

https://api.hatchways.io/assessment/blog/posts

Using node.js and https requests, I constantly receive an array of [ Promise { }, Promise { } ]. Unfortunately, I can only search by one tag at a time, and I have to retrieve a list of posts that has at least one tag from a list of provided tags, before sorting the posts. My code is below:

const express = require('express');
const app = express();

app.get("/api/ping", (req, res) => {
    res.status(200).send("{\"success\": true}");
})

app.get("/api/posts", (req, res) => {
    const tags = req.query.tags;
    const sortBy = req.query.sortBy;
    const direction = req.query.direction;

    if (!tags) res.status(400).send("Must provide at least one tag.");
    let tag_array = tags.split(',');
    let posts_array = [];
    tag_array.forEach(tag => {
        let posts = getPost(tag);
        posts_array.push(posts);
    })
    
    console.log(posts_array);
})

app.listen(3000, () => console.log("Listening on port 3000..."));

function getPost(tag) {
    const https = require('https');

    return new Promise( (resolve, reject) => {
        const options = {
            hostname: 'api.hatchways.io',
            path: `/assessment/blog/posts?tag=${tag}`
        }
    
        let body = [];

        const req = https.request(options, res => {
            res.on('data', data => {
                body.push(data);
            });

            res.on('end', () => {
                try {
                    body = JSON.parse(Buffer.concat(body).toString());
                } catch (error) {
                    reject(error);
                }
                resolve(body);
            });
        });
    
        req.on('error', error => {
            reject(error);
        });
    
        req.end();
    }).then(function(data) { return data; }, function(error) { console.log(error) });
}

CodePudding user response:

the getPost method is returning a promise, just do this:

app.get("/api/posts", async (req, res) => {
    const tags = req.query.tags;
    const sortBy = req.query.sortBy;
    const direction = req.query.direction;

    if (!tags) res.status(400).send("Must provide at least one tag.");
    let tag_array = tags.split(',');
    const promises = [];
    tag_array.forEach(tag => {
        promises.push(getPost(tag))
    });
    posts_array = await Promise.all(promises)
    console.log(posts_array)
})

CodePudding user response:

Just wait for all promises to resolve using the await keyword.

app.get("/api/posts", async (req, res) => { // Add the async keyword

    //... Skipped some code for concision
    
    tag_array.forEach(tag => {
        let posts = getPost(tag);
        posts_array.push(posts);
    })
    
    await Promise.all(posts_array)    // Add this to await all promises to resolve
    console.log(posts_array);
})
  • Related