I've already messed around with Promises in it, but I'm new to them and I just can't figure out how to do it properly. At the moment, there's no point to the Promise, because it doesn't wait till the async $.get
completes.
Basically, each foreach
iteration has its own $.get
function, and I need to have them all complete and then continue to the part that has the "...gets albumart" console.log
.
$.get(id,function(data) {
//(there's some code here)
var getZippyUrls = new Promise(function(resolve) {
zippyarray.forEach(function(zippy) {
//(more code)
$.get(zippy.full, function(data) {
//^This is the foreach of $.gets
//(code's here)
});
resolve(zippyarray);
});
});
//This is my failed Promise ->
getZippyUrls.then(function(response) {
console.log("WE'RE OUT " + response.length);
response.foreach(function(d) {
console.log("Promise"+d.media);
});
console.log('eyyyyyy');
});
console.log("...gets albumart");
//Now after the previous stuff is done, move on
To keep track of multiple get-Requests you are using this way:
You always call the finished-function when a request gets an answer. The finished-function does the job when all gets done.
I know this is an old question but things have changed a bit recently.
If you're fine with using external libraries, the Bluebird promise library has a pretty good implementation for this: Promise.each.
E.g.
Today if I needed to do it sequentially - I would do it with
async/await
:In synchronous code, continuation is performed when the line ends
;
With promises, continuation is performed via
.then
. You were using a promise constructor and resolved it immediately, you did not wait for any task at all. I'd map my work into tasks and then either chain them with then or await them serially.Now we can execute them all sequentially:
Or better, serially: