我编写的代码看起来像:
function getStuffDone(param) { | function getStuffDone(param) {
var d = Q.defer(); /* or $q.defer */ | return new Promise(function(resolve, reject) {
// or = new $.Deferred() etc. | // using a promise constructor
myPromiseFn(param+1) | myPromiseFn(param+1)
.then(function(val) { /* or .done */ | .then(function(val) {
d.resolve(val); | resolve(val);
}).catch(function(err) { /* .fail */ | }).catch(function(err) {
d.reject(err); | reject(err);
}); | });
return d.promise; /* or promise() */ | });
} | }
Run Code Online (Sandbox Code Playgroud)
有人告诉我这个被称为" 延迟反模式 "或" Promise构造函数反模式 ",这个代码有什么不好,为什么这被称为 …
我来实现,由于在ECMAScript中6承诺允许异步功能同步编码,对于每一个代码的承诺载货件有一个同步的必然结果.例如:
var data = processData(JSON.parse(readFile(getFileName())));
Run Code Online (Sandbox Code Playgroud)
是相同的:
var data = getFileName()
.then(readFile)
.then(JSON.parse)
.then(processData);
Run Code Online (Sandbox Code Playgroud)
现在,对于我目前的用例,我想编写代码来从大量的公共API中提取数据.API是分页的,所以在纯粹的同步世界中,我会写如下内容:
var data = [];
var offset = 0;
var total = 10000; // For example - not actually how this would work
while( offset < total ) {
data.concat(getDataFromAPI(offset));
offset = data.length;
}
Run Code Online (Sandbox Code Playgroud)
现在我的问题是,如何用承诺做到这一点?我可以这样写:
var data = [];
var offset = 0;
var total = 10000;
getDataFromAPI(offset)
.then(function(newData){
data.concat(newData);
return getDataFromAPI(data.length);
});
Run Code Online (Sandbox Code Playgroud)
但在这一点上,我被迫只是链接无限.thens - 没有循环逻辑.我觉得应该可以使用递归,但我不知道如何做到这一点.
我使用BluebirdJS作为我的诺言库,所以我可以访问他们所有的帮助方法.