tonymx227
tonymx227

Reputation: 5451

Promise function not returning results

I'm using instagram-scraping module to display all posts with a specific hash tag but I get an issue using a function to return finded items.

// in my middleware
function getInstagramPostsByHashTag(hashtag) {
  return ig.scrapeTag(hashtag).then(result => {
    console.log(result); // all posts are displayed in my console
    return result;
  });
}

// in my ejs template i send the function getInstagramPostsByHashTag()
<%=getInstagramPostsByHashTag("instagram")%> // nothing is displayed

Upvotes: 1

Views: 38

Answers (1)

grorp
grorp

Reputation: 353

You can't return the posts from the function because the function has already returned at this point. That's because .then() is asynchronous. It executes the provided callback when the work (fetching the posts) is done, but the function continues to run after the call to .then(), and because you return nothing, you get nothing.

If you want a function to return the result of an asynchronous operation, you have to return a promise from the function itself. To help developers with that, there's the async function that automatically returns a promise. In an async function, you can wait for other promises with the await keyword. Your function would look like this as an async function:

async function getInstagramPostsByHashTag(hashtag) {
  return await ig.scrapeTag(hashtag)
}

But this is redundant because it returns exactly the same as a direct call to ig.scrapeTag(hashtag) would do. I don't really know ejs but I think the best thing you could do is something like this (only pseudocode, again, I don't know how rendering with ejs works):

posts = insta.scrapeTag("blablabla")
    then
        ejs.render("<%=posts%>", {posts})

Upvotes: 1

Related Questions