Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript promise confusion

I'm trying to grasp the concept of javascript promise. But I'm getting some problems. I set up a very small web service locally(don't get angry, the web service does not conform to conventions). Here some details about it

/login/<username>/<password> ==> login into the system, the correct username and password is both noor

if user is login, a call can be made on /car/<brand>/<color>/<plate_number>,

I'm not performing any validation on the type of color,brand,platenumber

This one works perfectly fine, I'm logging and adding a car

$.ajax({type: "GET",url: url+"/login/noor/noor"})
                .then(function( data, textStatus, jqXHR ) {console.log("login success");},function(){console.log("login error");})
                .then($.ajax({type: "GET",url: url+"/car/1/1/1"}))
                .then(function(){console.log("car added");},function(){console.log("car not added");});

This one perfectly shows an error because an invalid url is used:

$.ajax({type: "GET",url: url+"/carasdsad/1/1/1"})
                .then(function(){console.log("car added");},function(){console.log("car not added");});

"/carasdsad/1/1/1" is an invalid url and car not added is returned

I'm getting a problem with this one. The code below uses the code just above. I was expecting car not added to be shown but its showing car added

$.ajax({type: "GET",url: url+"/login/noor/noor"})
                .then(function( data, textStatus, jqXHR ) {console.log("login success");},function(){console.log("login error");})
                .then($.ajax({type: "GET",url: url+"/carasdsad/1/1/1"}))
                .then(function(){console.log("car added");},function(){console.log("car not added");});

The above code is returning car added although "/carasdsad/1/1/1" is an invalid url in the second call.

like image 879
Noor Avatar asked Oct 01 '22 05:10

Noor


1 Answers

According to spec, non-function argument is ignored in then method.

Your code reduced to minimal case looks like that:

Promise.resolve(true)
    .then(Promise.reject("some err"))
    .catch(console.log.bind(console, "fail"));

And one need to rewrite it this way in order to catch errors:

Promise.resolve(true)
    .then(function(){ return Promise.reject("some err") })
    .catch(console.log.bind(console, "fail"));
like image 144
kirilloid Avatar answered Oct 05 '22 13:10

kirilloid