0

I am using Javascript fetch API to post data to a json server. But I am getting UnhandledPromiseRejection Warning. Below is the code, plese help in finding the issue in the code.

function addFavourite(movieid) {
        if (!favMovies.find(x => x.id == movieid)) {
            let movie=movies.find((x)=>x.id==movieid);
            //console.log(movie);
            //addFavourite(movie);
            return fetch("http://localhost:3000/favourites", {
                method: "POST",
                headers:{
                    "Contenet-Type": "application/json"
                },
                body: JSON.stringify(movie),
            }).then((response) => {
                favMovies.push(movie);
                return response.json();
            }).then((response)=>{
                return response;
            }).catch((error)=>{
                return (error);
            });;
        } else {
            throw new Error('Movie is already added to favourites');
      } 
}

(node:7358) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): AssertionError: AssertionError: expected { Object (voteCount, id, ...) } to deeply equal [ Array(2) ]: expected { Object (message, showDiff, ...) } to equal null (node:7358) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Suresh Prajapati
  • 3,991
  • 5
  • 26
  • 38
  • 2
    Your code looks good, but your error looks like you are using this in some test case, right? The problem will be in your assert, not in the addFavourite method. – Martin Adámek Sep 10 '18 at 17:55
  • Assertion error? Where does that come from? Please show us the code where you are *calling* `addFavourite` – Bergi Sep 10 '18 at 18:53
  • [`.then((response)=>{ return response; })` is pointless](https://stackoverflow.com/q/41089122/1048572), and you should not do `.catch((error)=>{ return (error); })` as that doesn't really handle anything but returns an error as if it was a fulfillment result. Also [don't `throw` from a function that would return a promise](https://stackoverflow.com/questions/21887856/should-an-async-api-ever-throw-synchronously). – Bergi Sep 10 '18 at 18:54

0 Answers0