2015-07-28 54 views
2

我有一個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

+0

什麼答應你是什麼意思? [native Promise](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise)還是來自某個庫? – Grundy

+0

@Grundy告訴你實話我不確定......我認爲原生將是這裏最輕的選擇(或者我錯了嗎?)它將如何支持IE9? – FireBrand

+0

mdn說IE不支持承諾,甚至11.我的意思是天生的承諾。也正如我看到jqlite - 沒有自己的承諾? – Grundy

回答

2

如何使用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 
    }); 
}); 
+0

我將如何處理MyClass.prototype.mySpecialFunction'''之外的東西爲了完成?匿名函數中的'''return''會工作嗎? – FireBrand

+1

@FireBrand更新後的代碼,改爲'return getJSONP..' – mido

+0

好吧,那麼對'''mySpecialFunction''的調用應該如何從'''MyClass.mySpecialFunction(myObject)'''改變? – FireBrand