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

孤人 提交于 2019-12-05 19:01:34

问题


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


回答1:


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/




回答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



来源:https://stackoverflow.com/questions/27550394/how-to-fetch-value-from-promise-object-after-promise-has-been-resolved

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!