1

How to do asynchronous operation using for loop and promise without arrow function and aysnc/await I have array, iterate through it in synchronously. during async task as in below code, i value to be executed synchronously(example: say when i value is 2, wait until async task is finished, once async response comes move to next value of i, if validations of if conditions fails)

array = [{a:1,b:0,c:3,d:3},{a:1,b:0,c:0,d:5},{a:1,b:2,c:3,d:2},{a:1,b:2,c:3,d:error}]
for (var i =0 ;i<=array.length;i--){
    if (array[i].d == 'error'){
        console.log("D's Value is Error");
        return false;
    }
    if(array[i].a == 0){
        console.log("A is Zero");
        return false;
    }

    if (array[i].b == 0 && array[i].c == 0){
        //do async task using promise based on response return the value back
        Promise.then(function(response){
            if (!response){
                return false
            } else {
                return true;
            }
        }).catch(function(err){
            return false;
        });
    }
}
  • 1
    Why don't you want to use `await`? It should work as expected: https://stackoverflow.com/a/37576787/2357085. – w08r Jan 26 '20 at 15:42
  • 1
    You can't do what you've said you want to do. The thing about asynchronous tasks is...they're asynchronous. :-) Your `for` loop is synchronous. There's nothing you can do to make most asynchronous tasks synchronous, and there's nothing you can do with a JavaScript promise that lets you get its result synchronously. You *can* make the `for` loop asynchronous, but that would require using what you've said you don't want to use / can't use: `async`/`await`. So you'll **have** to change the code to embrace the asynchronousness, probably by having it return a promise. – T.J. Crowder Jan 26 '20 at 15:44
  • I'm guessing you want to avoid `async`/`await` because you have to support obsolete browsers. But you can still use `async`/`await` even if you need to do that, by using a transpiler like [Babel](https://babeljs.io) to transpile the code into something obsolete browsers can execute. – T.J. Crowder Jan 26 '20 at 15:45
  • async/await doesnot support while compiling the app build neither arrow functions. if for loop can be made asynchronous. that would also be fine. help – sachin_ghagare Jan 26 '20 at 15:53

0 Answers0