Search code examples
javascriptecmascript-6es6-promiseecmascript-5

Unknown Error while using Javascript promises


I am new to Javascript and trying to understand how promises work. I have written the below code to call a REST API and resolve the response.

const buyFlightTicket = () => {
    return new Promise( (resolve, reject) => {
        setTimeout( () => {
            let commentResponse = fetch('https://jsonplaceholder.typicode.com/comments/1'); 
            commentResponse
                .then(response => {
                    if (response.status == 200) {
                        resolve(response.json());
                    } else {
                        reject("Failed to fetch comment: " + response.statusText);
                    }
                })
                .reject("Failed to fetch comment");
        }, 3000);
    })
}

buyFlightTicket()
.then( (responseData) => console.log(responseData))
.catch( (error) => console.log(error));

I am able to log the response data but I am getting Error: Unknown error just before the response is being logged to the console.

What is causing this error?

Also, how do i rewrite this code using callbacks without using Promise?


Solution

  • You should use the catch, not .reject

                commentResponse
                    .then(response => {
                        if (response.status == 200) {
                            resolve(response.json());
                        } else {
                            reject("Failed to fetch comment: " + response.statusText);
                        }
                    })
                    .catch(() => "Failed to fetch comment");