且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在没有延迟的Anit模式的情况下将jQuery $ .ajax调用转换为Bluebird Promise

更新时间:2022-05-15 00:59:56

您可以调用

You can call Promise.resolve on a jQuery thenable and have Bluebird assimilate it:

var res = Promise.resolve($.get(...)); // res is a bluebird Promise

您还可以直接在Bluebird链中返回jQuery Promise,并将其吸收.

You can also return jQuery promises directly inside a Bluebird chain and have it assimilate it.

myBluebirdApi().then(function(){
    return $.get(...);
}).then(function(result){
    // The jQuery thenable was assimilated
});

您的以下代码已结束,但是您无需抓住TimeoutError,因为jQuery ajax不会抛出这些.至于捕捉取消错误.无论如何,这都是***做法,以防您需要取消请求.

Your code below is close, but you don't need to catch TimeoutError since jQuery ajax won't throw those. As for catching cancellation error. This is best practice anyway for what you're doing if you ever expect to need to cancel the request.