The problem of asynchronous operation

the for loop sends multiple requests in one function, so how to wait until the request is all returned to execute the next function, because the next function uses the return value.

Apr.06,2021
In

for, put each request into a promise, then put the promise push into an array, and finally use let result = await Promise.all (promise array); , result contains all the return values.


the easiest way is to use async+await combined with Promise.all to achieve it, as mentioned on the 1st floor. I'll provide another primitive method for your reference.
in addition, the request result is cached with a new array, and the result is obtained asynchronously and saved to the array. When the length of the cache array is the same as the request length, it means that the request has all returned and is ready to perform the next step

const result = [];
const request = [1, 2, 3, 4, 5];
request.forEach(id => {
  axios.get(`/user?ID=${id}`).then(res => {
    result.push(res);
    if (result.length === request.length){
      //
    } 
  })
})

if it is a vue project, some asynchronous problems can be solved with watch snooping


1. As mentioned above, create an array that holds the result state, and assume that the number of ajax you want to loop is ajax_count
var result = [];
2. Declare a callback function for ajax that executes another function based on the state of the result array (that is, what needs to be executed after the ajax is all executed)
function on_all_ajax_finished ()
{

console.log("ajax");

}

function ajax_callback ()
{

ifresult.length == ajax_count -1
{
    on_all_ajax_finished();
}
else
{
    result.push(1);//pushjs
}

}

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-1b3bd47-4ef2c.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-1b3bd47-4ef2c.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?