我是整套延迟/承诺原则的新手,但在阅读后我能找到的所有内容都是关于如何使用它们返回ajax数据,而不是JavaScript对象。那可能吗?我们的目标是使下面的代码工作:我可以做一个承诺返回jQuery中的填充对象吗?
var Binary = function(data){
this.data = data;
}
var File = function(url){
this.data = null;
this.url = url;
this.getData = function(){
// return either cached version at this.data or fetch it
}
}
// the goal is to make the following possible:
var url = "http://www.google.com/humans.txt";
var file = new File(url);
file.getData().done(function(binary){ //binary should be equals to `new Binary(data)`
alert("we got binary data object with the data being: " + binary.data);
});
如果你的操作有时异步有时同步的,那么你就可以回到一个早已解决的承诺的同步路径,然后主叫可以把结果看作是异步的,或者不是。如果结果总是同步产生,那么没有理由使用承诺。 – jfriend00 2014-12-07 19:31:47
哪个诺言味道,你想在答案? ['jQuery.deferred'](http://api.jquery.com/jQuery.Deferred/)? [ES6承诺](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)?承诺/ A +? – 2014-12-07 19:32:17
@FabrícioMattéjQuery.deferred – chacham15 2014-12-07 19:32:39