I have been using promises for a while, but now and then I stumble into problems that I cannot seem to resolve (no pun intended).
I have an array of files for which I have to perform asynchronous functions call for each file to fetch some metadata.
I'm using RSVP.hash()
and pass an array of promises returned by a function that load some metadata and adds it as a properties to the file. My problem is that the promise returned by the hash()
function is resolved before any of the passed promises are resolved, and thus, it enters the then()
function all too soon.
I've created a JSfiddle that illustrates my problem. I've explored the possibility that this is not due to RSVP, but instead of how the JavaScript interpreter reads the code, and perhaps does an immediate evaluation of the part I thought would run last.
Am I using RSVP.hash()
the wrong way, missing something, or have any other errors in my code that would cause it to behave this way instead of what my intentions are?
The below code snippet is the same as the JSFiddle.
function checkFileStatus(item) {
return new RSVP.Promise(function(resolve, reject) {
setTimeout(function() {
$('#list').append("<li>Checking status for " + item.title);
resolve();
}, 1000);
});
}
function init() {
var fileList = [{
title: "First object"
}, {
title: "Second object"
}, {
title: "Third object"
}];
var statusCheck = fileList.map(function(item) {
return checkFileStatus(item);
});
var promises = {
promisesCheckFileStatus: statusCheck
};
RSVP.hash(promises).then(function() {
$('#list').append("<li>This should happen last!");
});
}
init();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="//cdn.jsdelivr.net/rsvp/3.0.6/rsvp.js"></script>
<div>
<ul id="list"></ul>
</div>