skip to Main Content

I have a function and its have nested two ajax call. I want to return a value inside from second ajax call when ajax call is successed. i think because function ending but the ajaxs call still not end. But i didn’t solve it.

I prepared a example code below:

        
    var patato = function(){
            $.ajax({
                type: 'POST',
                url: 'https://jsonplaceholder.typicode.com/posts',
                dataType: 'json',
                data: {
                    title: 'foo',
                    body: 'bar',
                    userId: 1,
                },
                success:function(res){
                    console.log("Work 1")
                    $.ajax({
                        type: 'POST',
                        url: 'https://jsonplaceholder.typicode.com/posts',
                        dataType: 'json',
                        data: {
                            title: 'foo',
                            body: 'bar',
                            userId: 1,
                        },
                        success:function(res){
                            console.log("Work 2")
                            return true;
                        }
                    })
                }
            })
            console.log("Çalıştı 3")
        }
        var patatos = patato();
        if(patatos) {
            console.log("Patato true")
        }else{
            console.log("Patato false")
        }
<script src="https://code.jquery.com/jquery-3.7.0.min.js" integrity="sha256-2Pmvv0kuTBOenSvLm6bvfBSSHrUJ+3A7x6P5Ebd07/g=" crossorigin="anonymous"></script>

3

Answers


  1. Your function should return a promise since you are doing some async work (fetching).

    Also I strongly recommend to use async/await to simplify logic and improve readability/maintainability:

    async function patato() {
    
        console.log("Çalıştı 3")
    
        const res = await $.ajax({
            type: 'POST',
            url: 'https://jsonplaceholder.typicode.com/posts',
            dataType: 'json',
            data: {
                title: 'foo',
                body: 'bar',
                userId: 1,
            }
        });
    
        console.log("Work 1")
    
        //use res if needed...
    
        const res2 = await $.ajax({
            type: 'POST',
            url: 'https://jsonplaceholder.typicode.com/posts',
            dataType: 'json',
            data: {
                title: 'foo',
                body: 'bar',
                userId: 1,
            },
        });
    
        console.log("Work 2")
    
        //use res2 if needed...
    
        return true;
    
    }
    
    patato().then(patato => console.log(`Patato ${patato}`));
    <script src="https://code.jquery.com/jquery-3.7.0.min.js" integrity="sha256-2Pmvv0kuTBOenSvLm6bvfBSSHrUJ+3A7x6P5Ebd07/g=" crossorigin="anonymous"></script>
    Login or Signup to reply.
  2. First thing that I wanted to mention is that it will not make much sense to make sequential requests if you second request don’t need the response from the first one. On that note, I will assume you have a use case that requires two API call executed one after the other.

    Here you have two options: use callbacks or async/await syntax.
    Here you can find a good example of the usage of both: How to return an Ajax result using async/await?

    For your particular example here’s how you could do this with callbacks:

            
        const patato = function(){
                return $.ajax({
                    type: 'POST',
                    url: 'https://jsonplaceholder.typicode.com/posts',
                    dataType: 'json',
                    data: {
                        title: 'foo',
                        body: 'bar',
                        userId: 1,
                    }
                }).then(function(res1){ 
                    console.log("Work 1")
                        return $.ajax({
                            type: 'POST',
                            url: 'https://jsonplaceholder.typicode.com/posts',
                            dataType: 'json',
                            data: {
                                title: 'foo',
                                body: 'bar',
                                userId: 1,
                            }
                        }).then(function(res2){
                            console.log("Work 2")
                            return res1 && res2;
                        })
                })
            }
            patato().then(patatos => {
              if(patatos) {
                  console.log(patatos)
              }else {
                  console.log("Patato false")
              }
            })
    <script src="https://code.jquery.com/jquery-3.7.0.min.js" integrity="sha256-2Pmvv0kuTBOenSvLm6bvfBSSHrUJ+3A7x6P5Ebd07/g=" crossorigin="anonymous"></script>

    Or you could use async/await syntax as well (IMO this is easier to follow than the callback one):

       
    
        const patato = async function(){
                console.log("Work 1");
                const res1 = await $.ajax({
                    type: 'POST',
                    url: 'https://jsonplaceholder.typicode.com/posts',
                    dataType: 'json',
                    data: {
                        title: 'foo',
                        body: 'bar',
                        userId: 1,
                    }
                });
    
                console.log("Work 2");
                const res2 = await $.ajax({
                    type: 'POST',
                    url: 'https://jsonplaceholder.typicode.com/posts',
                    dataType: 'json',
                    data: {
                        title: 'foo',
                        body: 'bar',
                        userId: 1,
                    }
                });
                return res1 && res2;
    
            }
            async function test() {
                let result = await patato();
                console.log(result);
            }
            test();
    <script src="https://code.jquery.com/jquery-3.7.0.min.js" integrity="sha256-2Pmvv0kuTBOenSvLm6bvfBSSHrUJ+3A7x6P5Ebd07/g=" crossorigin="anonymous"></script>
    Login or Signup to reply.
  3. You can also run both AJAX jobs in parallel if the output of the first job is not required for the second one:

    async function patato() {
    
        console.log("Çalıştı 3")
        await $.when( $.ajax({type:'POST',url: 'https://jsonplaceholder.typicode.com/posts',
                             dataType:'json',data: {title: 'foo1',body: 'bar1',userId: 1}}),
                      $.ajax({type: 'POST',url: 'https://jsonplaceholder.typicode.com/posts',
                             dataType:'json',data: {title: 'foo2',body: 'bar2',userId: 2}})
        ).done(function([r1],[r2]){console.log("Both AJAX jobs are finished.",r1,r2)})
        console.log("End of patato.");
        return true;
    }
    
    patato().then(pa => console.log(`Patato returns ${pa}`));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search