N
N
Ninja Mate2016-11-22 23:19:56
JavaScript
Ninja Mate, 2016-11-22 23:19:56

What is the correct way to use Promise AJAX?

there are several similar functions, I want to run them all at the same time and wait for the last one to complete through Promise.all

getTotalGender(){
        
        var that = this;
     
        jQuery.post(

            MyAjaxChart.ajaxurl,
            {
                dataType: 'json', 
                'action': 'ReportGenderTotal',
                async: true
            }
        ).error( ( response )=> console.log( response )
        ).done( ( response )=> {
//нужно дождаться выполнения в Promise.all
                var myArray = JSON.parse( response );

                that.setState({ datasetGender: myArray });
           
            }
        );
    }

and want to run them
Promise.all( [ this.getTotalGender(), ... ] ).then( ()=> {
            
            console.log('this.state.datasetGender');
            console.log(this.state.datasetGender);//пустое значение, тк Promise не ждет полного выполнения
            
            this.setState({ ReportGender: <ReportGender
                dataset = { this.state.datasetGender }
            /> });
            
        });

How to do this?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vitaly, 2016-11-22
@victorzadorozhnyy

Wrap ajax in a promise, and then work like in the tutorial.
Only with promise all there is a catch, if 1 of the promises gives a reject, then all other promises will be lost.

getTotalGender(){
        var that = this;
        return new Promise((resolve, reject)=>{
                 jQuery.post(

            MyAjaxChart.ajaxurl,
            {
                dataType: 'json', 
                'action': 'ReportGenderTotal',
                async: true
            }
        ).error( ( response )=> {reject(response)}
        ).done( ( response )=> {
                      //нужно дождаться выполнения в Promise.all
                      resolve(response);
             });
});

Now we have a promise and we can stuff it into the promise all...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question