如何在promise中传递参数

Yog*_*esh 0 javascript jquery promise

我正在使用这样的承诺:

var restClient = {
    serveRequest: function(rUrl, type, body, rHeaders, rAsync, callback) {  
        var promise = jQuery.ajax({
           url: rUrl,
           type: type,
           data: body,
           headers: rHeaders,
           async: rAsync,
           contentType: "text/plain",
           dataType: "json"
        });

        promise.then(onSuccess, onError);   
    },
    onSuccess: function(data) {
        callback(data);
    },
    onError: function(msg) {
        console.log(msg.responseText);
    }
}
Run Code Online (Sandbox Code Playgroud)

如何在promise.then onSuccess中传递参数(回调)?我想稍后在onSuccess方法中使用它.

Ber*_*rgi 6

我正在使用这样的承诺

嗯,首先,你不应该.promises的目的是作为异步函数的结果返回,这样你就不再需要回调参数了.你最好这样做

var restClient = {
    serveRequest: function(rUrl, type, body, rHeaders, rAsync) {  
        var promise = jQuery.ajax({
           url: rUrl,
           type: type,
           data: body,
           headers: rHeaders,
           async: rAsync,
           contentType: "text/plain",
           dataType: "json"
        });
        return promise;
    }
};
Run Code Online (Sandbox Code Playgroud)

并让调用者restClient.serveRequest(…)调用.then(…).

如何在promise.then onSuccess中传递参数(回调)?

你不需要那个onSuccess.只是直接使用

promise.then(callback, function(msg) {
    console.log(msg.responseText);
});
Run Code Online (Sandbox Code Playgroud)

我想稍后在onSuccess方法中使用它.

你不能.它试图使用callback,但这是该serveRequest方法的本地参数- 因此onSuccess最多只能是一个本地函数,而不是它自己的方法.