Resolve promise when all images are loaded - javascript

I was preloading images with the following code:
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();
I thought images were all loading correctly because I could see the 'Resolved' log.
Later somebody pointed out that the code above doesn't guarantee that all images are loaded before resolving the promise. In fact, only the first promise is resolved.
I was advised to use $q.all applied to an array of promises instead.
This is the resulting code:
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();
This works, but I want to understand:
what's happening in each function;
why I need $q.all to make sure all images are loaded before resolving the promises.
The relevant docs are somewhat cryptic.

Check out this plunkr.
Your function:
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;
});
}
The idea is very similar to Henrique's answer, but the onload handler is used to resolve each promise, and onerror is used to reject each promise.
To answer your questions:
1) Promise factory
$q(function(resolve,reject) { ... })
constructs a Promise. Whatever is passed to the resolve function will be used in the then function. For example:
$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"
})
2) $q.all is passed an array of promises, then takes a function which is passed an array with the resolutions of all the original promises.

I'm not used to angular promise library, but the idea is as follows:
function getImagePromise(imgData) {
var imgEl = new Image();
imgEl.src = imgData.imgPath;
return $q(function(resolve, reject){
imgEl.addEventListener('load', function(){
if ((
'naturalHeight' in this
&& this.naturalHeight + this.naturalWidth === 0
)
|| (this.width + this.height == 0)) {
reject(new Error('Image not loaded:' + this.src));
} else {
resolve(this);
}
});
imgEl.addEventListener('error', function(){
reject(new Error('Image not loaded:' + this.src));
});
})
}
function preLoad() {
return $q.all($scope.abbreviations.map(getImagePromise));
}
// using
preLoad().then(function(data){
console.log("Loaded successfully");
data.map(console.log, console);
}, function(reason){
console.error("Error loading: " + reason);
});

Related

Promise returning unexpectedly

I have the following:
return indexedDbClient.getStorageUsedInGb().then(function (storageUsedInGb) {
var evictedMediaGuids = [];
storageUsedInGb = parseFloat(storageUsedInGb);
if (storageUsedInGb > storageQuotaInGb) {
return new Promise(function(resolve, reject){
const store = database.transaction(storeName, "readwrite").objectStore(storeName);
(function loop(storageUsedInGb) {
if (storageUsedInGb <= storageQuotaInGb) {
resolve({
evictedMediaGuids: evictedMediaGuids,
shouldStopStoring: false
});
} else {
const latestMediaRequest = store.getAll();
latestMediaRequest.onsuccess = function (event) {
const allData = event.target.result;
const targetEntry = allData[0];
const deleteRequest = store.delete(targetEntry.media.guid);
evictedMediaGuids.push(targetEntry.media.guid);
deleteRequest.onsuccess = loop.bind(null, storageUsedInGb - event.target.media.size / 1024 / 1000 / 1000);
deleteRequest.onerror = reject;
}
latestMediaRequest.onerror = reject;
}
})(storageUsedInGb); // call immediately
})
} else {
return Promise.resolve({
evictedMediaGuids: evictedMediaGuids,
shouldStopStoring: false
});
}
}).then(function (storeObject) {
// do stuff to object
return Promise.resolve(storeObject)
});
The idea is that loop(storageUsedInGb) forces the resolution to wait for the return; however handleStoreObject gets invoked immediately after loop - with no sign of the latestMediaRequest onsuccess handler being invoked. What am I doing wrong?
I am using bluebird in case it matters.

How to write my function with Promises

I am load HTML (external app) into an iFrame
I want to "do" something (callback) when an element becomes available in my iFrame. Here how I wrote it, and I'd like to write this with Promises instead:
function doWhenAvailable(selector, callback) {
console.warn("doWhenAvailable", selector)
if ($('#myiFrame').contents().find(selector).length) {
var elt = $('#myiFrame').contents().find(selector);
console.info("doWhenAvailable Found", elt)
callback && callback(elt);
} else {
setTimeout(function() {
doWhenAvailable(selector, callback);
}, 1000);
}
}
Actually instead of using setTimeout, I'd like to use setInterval to repeat the "find element" until it's found and resolve the "promise".
No, you would not use setInterval, you just would wrap the timeout in a promise and drop the callback:
function wait(t) {
return new Promise(function(resolve) {
setTimeout(resolve, t);
});
}
function whenAvailable(selector) {
var elt = $('#myiFrame').contents().find(selector);
if (elt.length)
return Promise.resolve(elt);
else
return wait(1000).then(function() {
return whenAvailable(selector);
});
}
Keeping your recursive style, it would have become something like that :
function doWhenAvailable(selector) {
var dfd = jQuery.Deferred();
console.warn("doWhenAvailable", selector)
if ($('#myiFrame').contents().find(selector).length) {
var elt = $('#myiFrame').contents().find(selector);
console.info("doWhenAvailable Found", elt)
return dfd.resolve(elt);
} else {
setTimeout(function() {
doWhenAvailable(selector).then(function(e) {
dfd.resolve(e);
});
}, config[env].wrapper.timeOutInMs);
}
return dfd.promise();
}
But I would have tried to avoid recursive calls here
The general idea is to return a promise instead of receiving a callback.
Example:
var xpto = function(res) {
return new Promise((resolve, reject) => {
if(res > 0) resolve('Is greater');
else reject(new Error('is lower'));
});
}
So in your case:
function doWhenAvailable(selector) {
function work(callback) {
if ($('#myiFrame').contents().find(selector).length) {
var elt = $('#myiFrame').contents().find(selector);
console.info("doWhenAvailable Found", elt)
callback(elt);
}
}
return new Promise((resolve, reject) => {
console.warn("doWhenAvailable", selector)
setInterval(() => work(resolve), 1000);
})
}
Here:
function doWhenAvailable(selector) {
return new Promise(function(resolve, reject){
console.warn("doWhenAvailable", selector)
if ($('#myiFrame').contents().find(selector).length) {
var elt = $('#myiFrame').contents().find(selector);
console.info("doWhenAvailable Found", elt)
resolve(elt);
} else {
setTimeout(function() {
doWhenAvailable(selector).then(function(data){
resolve(data);
});
}, config[env].wrapper.timeOutInMs);
}
}
}
And call your function like that:
doWhenAvailable("#elemId").then(function(elt){
//do what you want
});

Promise does not resolve node.js

I am trying to resolve some promises by the sendRequest function but it does not work.
For example, if I evoke sendRequest function 4 times, all of the times, I can see the log printed in the console and then going to resolve(data). But only 1 out of 4 times, the program reaches in to sendRequest.then().
Here is the complete code of that file.
change-name.js
var sendRequest = function(fileName){
return new Promise(function (resolve,reject) {
httpRequest(fileName).then(function (data) {
try{
if(.....){
if(.....){
var lastIndex = ....;}
if(.....){
var lastIndex = ....;}
str = fileName.substring(0, lastIndex);
if(.........){
sendRequest(str);}
else{
reject("this is the end");}
}
else{
console.log("end result" + JSON.stringify(data,null,4));
resolve(data);
//===== THIS RESOLVE DOES NOT WORK WHILE THE LOG PRINTS THE DATA =====//
}
}
catch(e){
resolve(data);
}
}).catch(function (err) {
reject(err);
});
});
};
server.js
this files calls the sendRequest function from the change-name.js and the then method is applied here for that function.
fs.readdir(path,(err,files)=>{
if(err){
console.log(err);
return;
}
for(i=0;i<files.length;i++){
sendRequest(files[i]).then(function (data) {
console.log(data + "\n");
}).catch(function(err){
console.log("end Error is " + err + "\n");
});
console.log(files);
}
});
The github link is "https://github.com/abhikulshrestha22/movierator".
Any help would be appreciated. Thanks
The problem is that one of your branches calls sendRequest again rather than resolving or rejecting, but then doesn't make any use of the promise the recursive call returns returns, so the promise you created for the outer call is never resolved. The inner one is (which is why you see the message in the console), but since nothing is using that promise, you don't get the result you expect.
There's also no need for new Promise in your code at all. httpRequest already gives you a promise, and your then handler on it creates a promise (if you return a value). So sendRequest should just return the result of calling then on httpRequest's promise, and within the then callback, either return the value to resolve the new promise with, or throw to reject. In the branch where you're calling sendRequest again, return the promise it returns; the one then creates will then resolve/reject based on that promise:
var sendRequest = function(fileName) {
return httpRequest(fileName).then(function(data) {
if (condition1) {
if (condition2) {
var lastIndex = something;
}
if (condition3) {
var lastIndex = somethingElse;
}
str = fileName.substring(0, lastIndex);
if (condition4) {
return sendRequest(str);
}
else {
throw new Error("this is the end");
}
}
else {
console.log("end result" + JSON.stringify(data, null, 4));
return data;
}
});
};
Here's a live example where httpRequest returns a random number 1-10, and if the number is less than 8, calls sendRequest again; it'll try up to three times before giving up:
function httpRequest() {
return new Promise(function(resolve) {
setTimeout(function() {
resolve(Math.floor(Math.random() * 10) + 1);
}, 500);
});
}
var sendRequest = function(fileName, retries) {
if (typeof retries !== "number") {
retries = 3;
}
return httpRequest(fileName).then(function(data) {
console.log("`then` got: " + data);
if (data > 7) {
console.log("It's > 7, yay! We're done");
return data;
}
console.log("It's <= 7g");
if (--retries === 0) {
console.log("Out of retries, rejecting");
throw new Error("out of retries");
}
console.log("retrying (" + retries + ")");
return sendRequest(fileName, retries);
});
};
document.getElementById("btn").addEventListener("click", function() {
var btn = this;
btn.disabled = true;
console.log("Sending request");
sendRequest("foo")
.then(function(data) {
console.log("Request complete: " + data);
})
.catch(function(err) {
console.log("Request failed: " + err);
// Because we don't throw here, it converts the rejection into a resolution...
})
.then(function() {
// ...which makes this kind of like a "finally"
btn.disabled = false;
});
}, false);
<input type="button" id="btn" value="Start">

Why isn't my promise getting resolved?

I have two functions - A helper function for downloading files which is as follows
var downloadHelper = function(url, saveDir) {
var deferred = Q.defer();
setTimeout(function() {
deferred.resolve("success");
}, 2000);
return deferred.promise;
}
Now I have a list of files to be downloaded in parallel. I have the logic for that function as follows:
var downloadAll = function() {
var fileDownloadList = []
for(var key in config.files) {
var deferred = Q.defer();
var saveLocation = __base + config.localDir
downloadHelper(
config.files[key],
saveLocation
).then(function() {
deferred.resolve("downloaded: " + fileUrl);
}).catch(function(err) {
deferred.reject(err);
});
fileDownloadList.push(deferred.promise);
}
Q.all(fileDownloadList).done(function() {
console.log("All downloaded");
},function(err) {
console.log(err);
});
setTimeout(function() {
console.log(fileDownloadList);
}, 10000);
}
The done is never getting called!
For debugging purposes, I added a setTimeout that will be called after 10 seconds and what I see is that out of 2 files, the second promise is resolved and the first one is still in pending state.
Any ideas?
Thanks in advance
One way to make your code work
for(var key in config.files) {
(function() {
var deferred = Q.defer();
var saveLocation = __base + config.localDir
downloadHelper(
config.files[key],
saveLocation
).then(function() {
deferred.resolve("downloaded: " + fileUrl);
}).catch(function(err) {
deferred.reject(err);
});
fileDownloadList.push(deferred.promise);
}());
}
But since downloadhelper returns a promise, no need to create yet another one
for (var key in config.files) {
var saveLocation = __base + config.localDir
fileDownloadList.push(downloadHelper(
config.files[key],
saveLocation
).then(function () {
return("downloaded: " + fileUrl);
}));
}
You'll see I removed
.catch(function(err) {
deferred.reject(err);
})
That's redundant, it's the same as not having the catch at all

Excecute JavaScript function after previous one completes

I want to execute several JavaScript functions in a specific order (like below) and not until the previous function has completed. I have tried this so many ways. Any suggestions? Any help is so greatly appreciated, I have been stuck on this for so long. Thanks in advance!
function savedSearch(e){
applySearch1("ColumnA");
applySearch2("ColumnB");
applySearch3("ColumnC");
applySearch4("ColumnD");
applySearch5("ColumnE");
applySearch6("ColumnF");
}
To add in response to the other answer by Mohkhan, you can also use the async library.
https://github.com/caolan/async
That will keep you out of callback hell and make for a much easier to read list of functions.
You should use callbacks in all your applySearch* functions.
Like this.
function savedSearch(e){
applySearch1("ColumnA", function(){
applySearch2("ColumnB", function(){
applySearch3("ColumnC", function(){
applySearch4("ColumnD", function(){
applySearch5("ColumnE",function(){
applySearch6("ColumnF", function(){
// You are done
});
});
});
});
});
});
}
If use jquery, it has deferred objects which helps you deal with async functions.
Here is an example:
// Code goes here
$(document).ready(function() {
function Pipe() {
this.asyncTasks = [];
this.observers = {};
this.on = function(eventName, fn) {
if (!this.observers[eventName]) {
this.observers[eventName] = $.Callbacks;
}
this.observers[eventName].add(fn);
}
this.fire = function(eventName, data) {
if (this.observers[eventName]) {
this.observers[eventName].fire(data);
}
}
this.register = function(asyncFn, context) {
this.asyncTasks.push(new Task(asyncFn, context));
}
this.start = function() {
this.fire('start');
this._next();
}
this._next = function() {
var task = this.asyncTasks.shift();
if (task) {
task.execute().then($.proxy(this._next, this));
} else {
this.fire('end');
}
}
var Task = function(fn, context) {
this.fn = fn;
this.context = context;
this.execute = function() {
if (!this.fn) {
throw new Exception("Failed to execute.");
}
var promise = this.fn.call(context);
this.fn = null;
return promise;
}
}
}
var bookMoview = function() {
var dfd = jQuery.Deferred();
// Resolve after a random interval
setTimeout(function() {
dfd.resolve("The movie is booked");
console.log("The movie is booked");
}, Math.floor(400 + Math.random() * 2000));
// Return the Promise so caller can't change the Deferred
return dfd.promise();
}
var bookTaxi = function() {
var dfd = jQuery.Deferred();
// Resolve after a random interval
setTimeout(function() {
console.log("Taxi is booked");
dfd.resolve("Taxi is booked");
}, Math.floor(400 + Math.random() * 2000));
// Return the Promise so caller can't change the Deferred
return dfd.promise();
}
var pipe = new Pipe();
pipe.register(bookMoview);
pipe.register(bookTaxi);
pipe.start();
});

Categories