0
votes

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?

1
You really should learn about promises in general first. - Bergi
getFirstSearchResult returns a promise so you either chain a .then() stage or if you want to go the imperative way use await-async in an async function. - Redu
You cannot immediately log the url - it has not arrived yet. All you got is a promise for it, which will fulfill with the url in the future - and you can schedule a callback run when it is there: getFirstSearchResultUrl().then(resultUrl => { console.log(resultUrl); }); - Bergi
Is it possible to completely prevent the rest of the script from executing until the promise is resolved? Or I'll just have to put everything that requires its results in the then callback function? - Gary
No.. it's synchronous workflow. Even if you could, as @Bergi says you can not assign the resolution of a promise to a variable just like that. You either chain the promise with .then() or use the async-await abstraction - Redu

1 Answers

1
votes

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