简体   繁体   中英

How to fetch 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 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

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/

There is a trick, define an array or object and value it in then:

    let Result=[];
    let callImport = (load)=>{ 
        import('./component.js').
            then((Module)=>{
                load[0] = Module;
            });};
    callImport(Result);
    setTimeout(()=> console.log(Result[0]),10);

Here i used setTimeout as await to prevent print Result before promise execution finish. Here is Codepen sample without setTimeout : https://codepen.io/MNSY22/pen/NWPdvxd

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