我有一个从原型(prototype)函数内部调用的 getJSONP 函数。我将一个 JSON 对象传递给该函数并更改其中的值,我希望能够在准备好后使用更新的对象,但我似乎无法返回该对象,只能从回调中调用不同的函数并使用它那里。
我认为我理解 promise 的概念,但是我如何将我的函数更改为 promise 并在准备好时使用它?
这是 getJSONP 函数:
function getJSONP(url, success) {
var ud = '_' + +new Date,
script = document.createElement('script'),
head = document.getElementsByTagName('head')[0] || document.documentElement;
window[ud] = function(data) {
head.removeChild(script);
success && success(data);
};
url += '?callback=' + ud;
script.src = url;
head.appendChild(script);
};
这就是我使用它的方式:
MyClass.prototype.mySpecialFunction = function(myObject) {
getJSONP(myURL,function(data) {
//doing alot of stuff
...
//myObject.myArr = code the pushes a lot of stuff into an array
workWithTheNewArray(myObject) // where i work with the full array
});
});
请考虑到我没有使用 jQuery(因为性能和大小),但我正在使用 jqlite .
最佳答案
使用 pormise polyfill 怎么样? ,他们声称它是轻量级的并且支持 IE,那么你可以尝试下面的代码:
function getJSONP(url, success) {
return new Promise(function(resolve, reject){
var ud = '_' + +new Date,
script = document.createElement('script'),
head = document.getElementsByTagName('head')[0] || document.documentElement;
window[ud] = function(data) {
head.removeChild(script);
resolve(data);
};
url += '?callback=' + ud;
script.src = url;
head.appendChild(script);
});
};
MyClass.prototype.mySpecialFunction = function(myObject) {
return getJSONP(myURL).then(function(data) {
//doing alot of stuff
...
//myObject.myArr = code the pushes a lot of stuff into an array
workWithTheNewArray(myObject) // where i work with the full array
});
});
关于javascript - Promise 的 getJSONP 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31672683/