我有一個getJSONP函數正在從原型函數中調用。我傳遞一個JSON對象到該函數並更改其中的值,我希望能夠使用更新後的對象,但我似乎無法返回該對象,只能從回調中調用一個不同的函數並使用它那裏。將getJSONP函數轉換爲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。
什麼答應你是什麼意思? [native Promise](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise)還是來自某個庫? – Grundy
@Grundy告訴你實話我不確定......我認爲原生將是這裏最輕的選擇(或者我錯了嗎?)它將如何支持IE9? – FireBrand
mdn說IE不支持承諾,甚至11.我的意思是天生的承諾。也正如我看到jqlite - 沒有自己的承諾? – Grundy