我正在覆盖像这样的javascript函数:
(function() {
origFunc = aFunction;
aFunction = function() {
doRequest();
//return origFunc.apply(this);
};
})();
我知道我需要以&#34结束该功能;返回origFunc.apply(this)"为了执行原始功能。但是,当我执行请求时,我必须等到请求完成。这就是我写这个函数的原因:
doRequest: function()
{
try
{
if(window.XMLHttpRequest)
httpRequest = new XMLHttpRequest();
else if(window.ActiveXObject)
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
var url = anUrl, self = this;
httpRequest.onreadystatechange = function(data)
{
try
{
if(httpRequest.readyState == 4)
{
if(httpRequest.status == 200)
return origFunc.apply(self);
else if(httpRequest.status != 0 )
alert("Error while executing the request : "+httpRequest.status+"\r\nUrl : "+url);
}
}
catch(e)
{
}
};
httpRequest.open("GET", url);
httpRequest.send();
}
catch(err)
{
alert("Error : "+err);
}
}
你可以猜到,问题在于我不能做那样的事情。 你知道我怎么做吗?
答案 0 :(得分:0)
以下是如何处理包装异步函数的示例
// This simply calls the callback with some data after a second
// Could be an AJAX call for example
var doSomethingAsync = function (callback) {
setTimeout(function () {
callback({ some: 'data' });
}, 1000);
};
var fnThatMakesAsyncCall = function () {
// From the outside there is no way to change this callback
// But what if we need to intercept the async function to change the data given to it, or monitor it?
// Then we'd have to wrap the async function to wrap the callback.
var callback = function (data) {
console.log('Original', data);
};
doSomethingAsync(callback);
};
// Function to wrap another function and return the wrapper
var wrapFn = function (fn) {
// Create the wrapped function.
// Notice how it has the same signature with `callback` as the first argument
var wrapped = function (callback) {
// Here we get the original callback passed in
// We will instead wrap that too and call the original function with our new callback
var newCb = function (data) {
// This will run once the async call is complete
// We will as an example mutate the data in the return data of the callback
data.some = 'Wrapped it';
// Call the original callback with the changed data
callback.call(this, data);
};
// Run the function we wrap with the new callback we supply
fn.call(this, newCb);
};
// Return wrapped function
return wrapped;
};
// Will log Original {some: "data"}
fnThatMakesAsyncCall();
doSomethingAsync = wrapFn(doSomethingAsync);
// Will log Original {some: "Wrapped it"}
fnThatMakesAsyncCall();