How to implement the respective execution of Async/Await

function getTimeOut1() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve("===5000ms===");
        }, 5000);
    });
}

function getTimeOut2() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve("===2000ms===");
        }, 2000);
    });
}

how to achieve this (split execution) effect with async/await:

getTimeOut1().then(res => {
    console.log(res);
});

getTimeOut2().then(res => {
    console.log(res);
});
  • ordinary await will wait for the returned result of a to execute b-> 8000ms +
const a = await getTimeOut1();
const b = await getTimeOut2();
  • is in the form of Promise.all ([.p]). Although it is a parallel operation, it waits for the slowest execution before the result is returned. -> 5000ms +

so I didn"t figure out how to use async/await to implement regular parallel callbacks.

Nov.21,2021

async function logInOrder(urls) {
  // URL
  const textPromises = urls.map(async url => {
    const response = await fetch(url);
    return response.text();
  });

  // 
  for (const textPromise of textPromises) {
    console.log(await textPromise);
  }
}
In the code

above, although the argument to the map method is the async function, it is executed concurrently because only the async function is executed secondary internally and not externally. Await, is used inside the later for..of loop, so it is implemented to output sequentially.

I hope this answer can help you. Thank you for your advice!


you cannot use async/await to implement the parallel callback you want, because await can only resolve one promise (Promise.all eventually turns multiple Promise into one), that is, await can only solve one callback, which does not meet your need for multiple callbacks. If you want to call back multiple times, you can only use .then multiple times, or encapsulate it into a method similar to Promise.all and Promise.race (called Promise.every, for example). If the business is simple, it is recommended to use it directly twice. Then:

  

you two have no dependency, so just write two async functions. Of course, a function can only describe a set of Synchronize logic, and js does not have goto

.
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1e46283-44b9d.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1e46283-44b9d.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?