getJSONP function to a Promise
getJSONP function to a Promise
我有一个从原型函数内部调用的getJSONP函数。我正在传递一个JSON对象到该函数和改变它里面的值,我希望能够使用更新的对象后,它准备好了,但我似乎不能返回对象,只有从回调调用不同的函数,并在那里使用它。
我想我理解承诺的概念,但我怎么能把我的函数变成一个承诺,并在它准备好时使用它?
这是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。
如何使用承诺填充,他们声称它是轻量级的,支持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
});
});
相关文章:
- 使用promise和mongoose对文档进行排序
- 节点Js:How to catch a“;没有这样的文件或目录“;读取线模块出错
- 测试Angular Service解决错误回调中的promise
- 节点协同与生成器和Promise并行流量控制
- jQuery AJAX write to XML
- grep in JQuery to C#
- how to convert html <div> to pdf
- 根据是否解析了 Promise 从函数返回值
- 将一个方法转换为promise:Nodejs
- Node.js - POST to iFrame?
- 函数在promise被解析后被调用,但Jasmine未通过测试.为什么?
- SVG xml to image
- js promise没有正确关闭
- Angularjs使用“;这个“;promise内的关键字回调
- Advantages to DOMParser vs template & innerHTML
- AngularJS和promise值在调用本地函数时的效果-未定义
- how to split a string with ','
- Promise to string - [object Object] or [object Promise]?
- getJSONP function to a Promise
- Rxjs to Promise行为不同于可观察到的行为