Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
189
rated 0 times [  195] [ 6]  / answers: 1 / hits: 30592  / 10 Years ago, thu, december 18, 2014, 12:00:00

Please note This is a contrived example.



    function longFunc(){
var deferred = $.Deferred();

setTimeout(function(){
console.log(long func completed);
deferred.resolve(hello);
}, 3000);

return deferred.promise();
}

function shortAfterLongFunc(x){
console.log('short func completed with value: ' + x);
return {
a: x
};
}

processFurther(longFunc().then(shortAfterLongFunc)); // send the array for further processing


Problem



I am unable to figure out how to return any kind of object/function for further downstream processing after shortAfterLongFunc completes. I can console.log from shortAfterLongFunc but that's not what i require here.
Fiddle Here



Thanks for looking!



UPDATE:



Okay just to make my question slightly better...this is a simple use case I am looking at:



$.map(['H','E','L','L', 'O'], somefunc). // for each item in array apply somefunc function

function somefunc(x){ // gets called for each value 'H', 'E' etc. in the array by $.map()
var longfunc = function(y){
var deferred = $.Deferred();

setTimeout(function(){
console.log(long func completed);
deferred.resolve(y.toLocaleLowerCase());
}, 3000);

return deferred.promise();
};

var shortAfterLongFunc = function(x){
console.log('short func completed with value: ' + x);
return x;
}

// What should I do here
return longFunc(x).then(shortAfterLongFunc); // must return lower case char to the caller of someFunc

}


somefunc() lets say processes each element of Array to lower case. However, assume this processing takes a long time and async (think setTimeout).. hence a promise to ensure synchronous operation for each element...but on using promise I find myself not able return the transformed value


More From » jquery

 Answers
7

Just chain another then call, since shortAfterLongFunc returns new promise you can further work with it:



longFunc().then(shortAfterLongFunc).then(function(data) {
console.log('all is complted', data);
});


Demo: http://jsfiddle.net/ebt4pxxa/2/


[#68448] Tuesday, December 16, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
blaynetheoi

Total Points: 146
Total Questions: 116
Total Answers: 103

Location: India
Member since Thu, Apr 8, 2021
3 Years ago
;