0

Scenario: With Current implementation If call1 is success then Call2 will be called. Call2 is success then Call3 will be called.

Expected:

Once Call1 and Call2 completely done from array of all filedata some code and Call3 needs to be called at the end.I added code outside the loop but it is called before filedata finishes its loop. How exactly execute the some operation code... which needs to be processed with each filedata ajax response value and has to make Call3 only once.

 filedata = [1,2,3] ;
 $btn.on('click', function () {
     //some operation
    filedata.forEach(function (item, index) {
        var promise = new Promise(function (resolve, reject) {
            $.ajax({
                type: "POST",
                url: "/call1",
                data: item,
                async: false,
                cache: false,
                contentType: false,
                processData: false,
                success: function (data) {
                    setTimeout(function () {
                        resolve(data);
                    }, 1000);
                },
                error: function (e) {
                    reject();
                }
            });
        });
        promise.then(function (image) {
            $.ajax({
                type: "POST",
                url: "call2",
                data: JSON.stringify({
                }),
                cache: false,
                contentType: "application/json",
                processData: false,
                success: function (data) {
                    //current: some operation code which will call the func written for call3
                },
                error: function (e) {
                    reject();
                }
            });
        }, function (error) {
            reject();
        });
    
    });

    // tried: some operation code which will call the func written for call3
 })```
TamilRoja
  • 165
  • 1
  • 1
  • 13
  • Beware [the explicit promise constructor antipattern](https://stackoverflow.com/q/23803743/215552)! – Heretic Monkey Jul 24 '20 at 12:19
  • Does this answer your question? [How to execute promises sequentially, passing the parameters from an array?](https://stackoverflow.com/questions/43082934/how-to-execute-promises-sequentially-passing-the-parameters-from-an-array) – Heretic Monkey Jul 24 '20 at 12:22

3 Answers3

0

use async/await syntax

The big benefit of async/await is that it makes asynchronous code appear synchronous. As in, do this thing, wait for it to finish and then give the result and then do another ajax call.

For Example:

async function doAjax(args) {
    let result;

    try {
        result = await $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: args
        });

        return result;
    } catch (error) {
        console.error(error);
    }
}
Abu Sufian
  • 991
  • 1
  • 6
  • 15
0

I think you could combine 2 of the cool features on JS which are generators and async/await functions, example to demonstrate:

function* generateSequence() {
  yield new Promise((res) => res(2))
  yield new Promise((res) => res(4))
  return new Promise((res) => res(6))
}
 
async function ajaxCalls() {
  const gen = generateSequence()
  const call_1 = await gen.next().value
  if (call_1.error) throw 'error after call 1' 
  const call_2 = await gen.next().value
  if (call_2.error) throw 'error after call 2'
  const call_3 = await gen.next().value
  if (call_3.error) throw 'error after call 3'
  return call_3.data // or the response you want from your method
}

hope that helps you. feels free to reach out if something looks blur.

0

execute call3 on last iteration of call2

addded one logic

if(index == filedata.length -1 ) {
//Call3
}
TamilRoja
  • 165
  • 1
  • 1
  • 13