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

后端 未结 2 1101
难免孤独
难免孤独 2021-02-20 12:46

Please note This is a contrived example.

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

        setTimeout(function(){
            console.log(\"         


        
相关标签:
2条回答
  • 2021-02-20 13:09

    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

    0 讨论(0)
  • 2021-02-20 13:10

    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/

    0 讨论(0)
提交回复
热议问题