0

I wonder how to await the outcome of multiple async functions properly:

async function call1() {
    let result = await $.ajax({url: `api/call1`});
    data1 = result;
};

async function call2() {
    let result = await $.ajax({url: `api/call2`});
    data2 = result;
};

My approach:

let somevar = function () {
    call1().then( var1 => {
        call2().then( var2 => {

            console.log("call1", data1, "call2", data2);
        });
    });
};

This is how I tried it, and I am sure this is not the way how to do this.

xtlc
  • 1,070
  • 1
  • 15
  • 41
  • 1
    Possible duplicate of [How to return many Promises and wait for them all before doing other stuff](https://stackoverflow.com/q/31426740/218196). Don't use shared variables. With `Promise.all` you can do `Promise.all([$.ajax(...), $.ajax(...)]).then(([data1, data2]) => ...)` – Felix Kling Aug 29 '21 at 20:42
  • 1
    @xtlc Felix refers to those globals `data1` and `data2`. Do not use them. Just have the functions `return` the result value, and then `console.log("call1", var1, "call2", var2);` – Bergi Aug 29 '21 at 22:35

1 Answers1

0

You can use promise.all()

const [result1, result2] = await Promise.all([call1(), call2()]);
Peter Haight
  • 1,906
  • 14
  • 19
c-132
  • 1
  • 1
  • 5