Ad

Request-promise `.catch` Throwing Up An Error

- 1 answer

I want to ask a question about request-promise in nodeJS.

I'm new to nodeJS and so far I've produced the following code:

const rp = require('request-promise');

rp('https://jsonplaceholder.typicode.com/users/1')
    .then((htmlstring) => {
        console.log(htmlstring);
    });

This all works fine.

When I add a catch loop as below:

const rp = require('request-promise');

rp('https://jsonplaceholder.typicode.com/users/1')
    .then((htmlstring) => {
        console.log(htmlstring);
    });
    .catch((err) => {
        console.log('Error', err);
    }

I get an error.

I'm confused. I read a previous question where one solution to the issue was to add a parameter, but I did it in this case, which is err.

Why am I getting the following error?

/workspace/APIcourse/JSONplaceholder.js:8
        .catch((err) => {
        ^

SyntaxError: Unexpected token .
    at new Script (vm.js:80:7)
    at createScript (vm.js:274:10)
    at Object.runInThisContext (vm.js:326:10)
    at Module._compile (internal/modules/cjs/loader.js:664:28)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
    at Module.load (internal/modules/cjs/loader.js:600:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
    at Function.Module._load (internal/modules/cjs/loader.js:531:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:754:12)
    at startup (internal/bootstrap/node.js:283:19)
Ad

Answer

Your error is a syntax problem, you are including a semicolon after .then() but if you want to catch potential errors using catch you need to include .catch() and then insert the semicolon.

Correct syntax:

rp('https://jsonplaceholder.typicode.com/users/1')
    .then((htmlstring) => {
        console.log(htmlstring);
    }).catch((err) => {
        console.log('Error', err);
    };
Ad
source: stackoverflow.com
Ad