简体   繁体   中英

Why does my hash of promises resolve before passed promises resolve?

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> 

The object you're trying to resolve with hash() has an array filled with promises. hash only resolves keys/values that are promises itself.

So where you have this

var promises = {
    key: [promise1, promise2, promise3]
};

you should have

var promises = { key: PromiseThatWillResolveToOtherPromises };

Change

var promises = {
    promisesCheckFileStatus: statusCheck
};

to

var promises = {
    promisesCheckFileStatus: RSVP.all(statusCheck)
};

The hash part is not correct. The key promisesCheckFileStatus contains an Array and not a Promise. You need to do something like this:

 var promises = {
    promisesCheckFileStatus: checkFileStatus(fileList[0]),
    promisesCheckFileStatus1: checkFileStatus(fileList[1]),
    promisesCheckFileStatus2: checkFileStatus(fileList[2]),
 };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM