-2

When I sent this simple API request-promise call, I don't get any response. Can someone please tell me why this isn't working?

var request = require('request-promise');
var options = {
    uri: 'https://jsonplaceholder.typicode.com/todos/1',
    headers: {
        'User-Agent': 'Request-Promise'
    },
    json: true
};

request(options)
.then(function (success) {
    console.log(success);
})
.catch(function (error) {
    console.log('noob!');
})

It goes to the "request(options)" line, skips over BOTH the success and failure, and just exits out of the program. What gives?!

Jeff Bowman
  • 90,959
  • 16
  • 217
  • 251
  • 2
    Hello! Though I can understand how this could be frustrating, please understand that many people view this site at work and would appreciate less colorful language. I've edited out the extra so this question may be more useful to other readers and answerers in the future. – Jeff Bowman Apr 20 '20 at 21:57
  • What are you using to run this? NodeJS? In that case, which version? – abondoa Apr 20 '20 at 21:59

1 Answers1

1

As in the answer to your previous question, you are using a Promise, which is guaranteed to skip over the request and response. By passing in those two functions, you are offering your execution environment (presumably Node) callbacks that it can call once it successfully completes the request. Because you're accessing a remote server, this will take some time, typically in the tens or hundreds of milliseconds.

If you don't instruct Node otherwise, it will terminate when it reaches the end of your script. This may not be in time for the library to invoke your callback. As in this NodeJS issue, you can use a top-level await function, which pauses execution of your program to wait for the callback.

try {
  let success = await request(options);
  console.log(success);
} catch (error) {
  console.log('noob!');
}

See also: Node exits without error and doesn't await promise (Event callback)

Jeff Bowman
  • 90,959
  • 16
  • 217
  • 251