How to make the while loop finish executing the function output before moving on to the next loop?

how do I get the output of the function executed in the while loop before moving on to the next loop?
specifically, in the following example, how do you get f (list) to output the result before executing jPP, and then moving on to the next loop?

the problem is as above, and the code is as follows:

const f = () => {
    ...
}

let arr = ["abc", "def"]
let j=0;

while (j<arr.length) {
    const list = arr[j];
    f(list);
    jPP;
}
Mar.06,2021

how do I get f (list) to output the results before executing jPP, and then moving on to the next loop?

that's what it is. Even if you include an asynchronous method, you are finished executing the output, just not waiting for the asynchronous result to return.

const f = (list) => {
    return new Promise((reslove) => {
        setTimeout(() => {
            console.log(list);
            reslove();
        }, 1000);
    })
}

async function run() {
    let arr = ['abc', 'def']
    let j = 0;

    while (j < arr.length) {
        const list = arr[j];
        await f(list);
        console.log('j=', j);
        jPP;
    }
}

run();

const f = function (data) {
    return new Promise((res, rej) => {
        setTimeout(() => {
            //
            console.log(data);
            res("complete");
        }, 1000);
    });
}

let arr = ['abc', 'edf', 'ghi'];
let j = 0;

for (let i = 0; i < arr.length; iPP) {
    f(arr[i])
    .then(function (str) {
        console.log("j: " + j);
        jPP;
    });  
}

you can use Promise to wrap asynchronous operations and return on reslove, but the loop is uncontrollable and it will continue, so use for, or you will fall into a dead loop. It is possible to jPP after executing the f function


can be realized by recursion

      const f = (list) => {
        return new Promise((reslove) => {
          setTimeout(() => {
            console.log(list);
            reslove();
          }, 1000);
        })
      };

      function run() {
        let arr = ['abc', 'def'];
        let j = 0;
        
        loop();
        /**/
        function loop() {
          const list = arr[j];
          f(list).then(()=>{
            if(j < arr.length)
              loop();
          });
          console.log('j=', j);
          jPP;
        }
      }
      run();
    }
Menu