JavaScript承诺混乱 [英] JavaScript promise confusion

查看:70
本文介绍了JavaScript承诺混乱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力掌握javascript承诺的概念。但是我遇到了一些问题。我在本地设置了一个非常小的Web服务(不要生气,Web服务不符合约定)。这里有一些关于它的细节

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> ==>登录系统,正确的用户名和密码都是noor

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

如果用户登录,可以在 / car /< brand>上进行通话。 /< color> /< plate_number>

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

我没有对颜色,品牌,platenumber的类型进行任何验证

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是无效网址且未添加车辆返回

"/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");});

上面的代码返回汽车已添加虽然/ carasdsad / 1/11是第二次通话中无效的网址。

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

推荐答案

根据 spec ,在然后方法中忽略非函数参数。

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"));

这篇关于JavaScript承诺混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆