weixin_33670713 2018-08-29 20:18 采纳率: 0%
浏览 43

如何把它变成一个承诺?

I have this ajax call and I need to turn it into a promise.

function myRest(url, method, callback){
    return $.ajax({
        url : url,
        type : method,
        dataType: "json",
        contentType: "application/json",
        success: function(results){
            //things to do in case of success
                    },
        error: function (){
          //things to do in case of error           
}
    });
}

How could I also use the .then() method in case of success? Thanks

  • 写回答

1条回答 默认 最新

  • weixin_33691817 2018-08-29 22:23
    关注

    I have this ajax call and I need to turn it into a promise.

    $.ajax() already returns a promise. You can just use .then() on it already, return the promise and get rid of the callback. You don't need to "turn anything into a promise". It already is a promise. You can use that existing promise like this:

    function myRest(url, method) {
        return $.ajax({
            url : url,
            type : method,
            dataType: "json"
        });
    }
    
    myRest(...).then(function(results) {
        // success
    }, function(jqXHR, textStatus, errorThrown) {
        // error
    });
    
    评论

报告相同问题?