U r*_*u s 3 javascript angularjs angular-promise
我使用以下代码预加载图像:
function preLoad() {
var deferred = $q.defer();
var imageArray = [];
for (var i = 0; i < $scope.abbreviations.length; i++) {
imageArray[i] = new Image();
imageArray[i].src = $scope.abbreviations[i].imgPath;
}
imageArray.forEach.onload = function () {
deferred.resolve();
console.log('Resolved');
}
imageArray.forEach.onerror = function () {
deferred.reject();
console.log('Rejected')
}
return deferred.promise;
}
preLoad();
Run Code Online (Sandbox Code Playgroud)
我认为图像都正确加载,因为我可以看到“已解决”日志。
后来有人指出,上面的代码并不能保证在解决承诺之前加载所有图像。事实上,只有第一个承诺被解决了。
我被建议改用$q.all应用于一系列承诺。这是结果代码:
function preLoad() {
var imageArray = [];
var promises;
for (var i = 0; i < $scope.abbreviations.length; i++) {
imageArray[i] = new Image();
imageArray[i].src = $scope.abbreviations[i].imgPath;
};
function resolvePromises(n) {
return $q.when(n);
}
promises = imageArray.map(resolvePromises);
$q.all(promises).then(function (results) {
console.log('array promises resolved with', results);
});
}
preLoad();
Run Code Online (Sandbox Code Playgroud)
这有效,但我想了解:
$q.all确保在解决承诺之前加载所有图像。在相关的文档有些神秘。
看看这个plunkr。
你的功能:
function preLoad() {
var promises = [];
function loadImage(src) {
return $q(function(resolve,reject) {
var image = new Image();
image.src = src;
image.onload = function() {
console.log("loaded image: "+src);
resolve(image);
};
image.onerror = function(e) {
reject(e);
};
})
}
$scope.images.forEach(function(src) {
promises.push(loadImage(src));
})
return $q.all(promises).then(function(results) {
console.log('promises array all resolved');
$scope.results = results;
return results;
});
}
Run Code Online (Sandbox Code Playgroud)
这个想法与 Henrique 的答案非常相似,但是 onload 处理程序用于解析每个承诺,而 onerror 用于拒绝每个承诺。
回答您的问题:
1) 承诺工厂
$q(function(resolve,reject) { ... })
Run Code Online (Sandbox Code Playgroud)
构造一个 Promise。传递给resolve函数的任何内容都将在函数中使用then。例如:
$q(function(resolve,reject) {
if (Math.floor(Math.random() * 10) > 4) {
resolve("success")
}
else {
reject("failure")
}
}.then(function wasResolved(result) {
console.log(result) // "success"
}, function wasRejected(error) {
console.log(error) // "failure"
})
Run Code Online (Sandbox Code Playgroud)
2) $q.all 被传递一个承诺数组,then接受一个函数,该函数被传递一个具有所有原始承诺的分辨率的数组。
| 归档时间: |
|
| 查看次数: |
11261 次 |
| 最近记录: |