How to get value from Promise object after promise has been resolved

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 can not determine how to return any object / function for further subsequent processing after completion of shortAfterLongFunc . I can console.log from shortAfterLongFunc , but that is not what I need here. Fiddle here

Thanks for watching!

UPDATE:

Okay, just to make my question a little 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() allows you to process each element of the array in lower case. However, suppose this processing is time-consuming and asynchronous (I think setTimeout) .. hence the promise to provide synchronous operation for each element ... but, using the promise, I cannot return the converted value

+6
source share
1 answer

Just connect another then call, since shortAfterLongFunc returns new promises, you can continue working with it:

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

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

+5
source

Source: https://habr.com/ru/post/979866/


All Articles