Gary
Gary

Reputation: 4231

Wait for Bluebird promise to resolve before continuing

I'm using an NPM package called snoowrap, that accesses the Reddit API. It returns results, such as from searches, as Bluebird promises.

I have file reddit.js like this:

const snoowrap = require('snoowrap');

function getFirstSearchResultUrl() {
  // Actual Reddit API credentials not included.
  const r = new snoowrap({
    userAgent,
    clientId,
    clientSecret,
    username,
    password,
  });

  return r
    .search({
      query: 'query',
      subreddit: 'askreddit',
    })
    .then((posts) => {
      return posts[0].url;
    });
}

const resultUrl = getFirstSearchResultUrl();
console.log(resultUrl);

But console.log prints [chainable Promise] rather than the URL that is returned.

How can I get it to print the URL that was returned, instead of the promise? I looked through the docs and tried different Bluebird methods like .reflect() and .settle() but they didn't seem to work for me.

Is it possible to prevent the rest of the script from executing until the promise is completed?

Upvotes: 0

Views: 2109

Answers (1)

Muhammad Usman
Muhammad Usman

Reputation: 10148

Your getFirstSearchResultUrl() returns a promise. That's why you see that log statement printed. And promise is not resolved yet.

So,You can wait for it to resolve with async/await or you can log the returned results adding a callback to .then() with getFirstSearchResultUrl().

Something like getFirstSearchResultUrl().then(url=> console.log(url))

You can also await for your getFirstSearchResultUrl() to be resolved, get the results and log it

Something like

(async function(){
  var url  =  await getFirstSearchResultUrl();
  console.log(url);
})(); 

Upvotes: 1

Related Questions