Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
12
rated 0 times [  16] [ 4]  / answers: 1 / hits: 28912  / 10 Years ago, mon, april 14, 2014, 12:00:00

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

More From » loops

 Answers
30

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.



//I'm assuming
zippyarray; // array of Zippy objects

var tasks = zippyarray.map(function(zippy,i){
return function(){ // return a task on that zippy;
// basic logic here
return $.get({
// ajax request
}).then(function(data){
// process data like in your code
// possibly store later for later use too
return process(data); // return the processed data;
});
}
});


Now we can execute them all sequentially:



 var p = tasks[0](); // start the first one
for(var i = 1; i < tasks.length; i++) p = p.then(tasks[i]);
p.then(function(result){
// all available here
});


Or better, serially:



$.when.apply(tasks.forEach(function(t){ return t(); })).then(function(results){
// all done
})

[#71465] Saturday, April 12, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
eanskylerg

Total Points: 524
Total Questions: 107
Total Answers: 100

Location: Colombia
Member since Mon, May 2, 2022
2 Years ago
;