How do I make a nested loop continue only after a asynchronous function has been resolved or how do I extend ".then" beyond the scope

javascript promise
javascript nested promises
promise chaining
javascript await
promise then return value
javascript promise example
promise inside promise

I tried to prevent async problems with promises in the following code. By using a .then function everything within that function gets called after the function has been resolved. But now I have the problem that neither can I extend the scope of the ".then function" enough to include the bits after the second loop nor can I to my knowledge easily pause the code until the function has been properly resolved and THEN continue with the loop iteration.

Here's my main code(simplified):

let total = []
$.each(element, function(data) {
  //Some other code
  let out;
  $.each(element2, function(data2) {
    getZip(data2).then(function(txt){ //after everything has finished this get's called
      out = someFunction(txt,data2);

   console.log(total)//this gets called first 
  //some other code that does some stuff with total

Here's the getZip code which is asynchronous:

        function getZip(zipFile) {
            return new Promise(function (resolve, reject){
                zip = new JSZip()
                JSZipUtils.getBinaryContent("someURL/" + zipFile, function (err, data) {
                    if (err) {
                    JSZip.loadAsync(data).then(function (zip) {
                        return zip.file(zipFile.replace(".zip", "")).async("text"); //gets the file within the zip andoutputs as text
                    }).then(function (txt) {


I'd be happy if either the getZip code could be made synchronous or if the before mentioned could be done.

I do not think I fully understand the code you have written. However, I recommend you use Promise.all. Here is an example I have written that I hope helps guide you:

let total = [];
$.each([1,2,3,4], function (data) {
  // Some other code.
  let out;
  // Create a new promise so that we can wait on the getZip method.
  new Promise(function (resolve, reject) {  
    // Create a holder variable. This variable with hold all the promises that are output from the getZip method you have.
    let gZipPromises = [];
    $.each([5,6,7,8], function (data2) {    
      // Your getZip method would go here. wrap the call to getZip in gZipPromises.push to push all the returned promises onto the holding variable.
      gZipPromises.push(new Promise(function (resolve2, reject2) { 
        // Sample Code
        setTimeout(function () {
        }, 10);
        // End Sample Code.
    // Pass the holding variable to Promise.all so that all promises in the holding variable are executed before resolving.
    Promise.all(gZipPromises).then(function() { 
  }).then(function () {
    // This will be called only when all getZip promises are completed in the second loop.
<script src=""></script>

Promises chaining, What we did here is just several handlers to one promise. After one second it resolves, and the result (the argument of resolve , here it's result * 2 ) is Returning promises allows us to build chains of asynchronous actions. They can have an extended set of methods, but also be compatible with native� JavaScript async and await in loops 1st May 2019. Basic async and await is simple. Things get a bit more complicated when you try to use await in loops.. In this article, I want to share some gotchas to watch out for if you intend to use await in loops.

const elements = [[""],[""],[""]];
const totalOut = getAllZips(elements)
  .then(text =>
  .catch(error => console.error(error))

function someFunction(text, data) {
  return `${text}\nLength: ${data.length}`;

async function getAllZips(elements) {
  let promises = [];
  for(const element of elements) {
    for(const data of element) {
      promises.push(getZip(data).then(text => {
        return someFunction(text, data);
  return Promise.all(promises);

async function getZip(file) {
  return new Promise((resolve, reject) => {
    JSZipUtils.getBinaryContent(`someURL/${file}`, async (err, data) => {
      try {
        if (err) throw err;
        const zip = await JSZip.loadAsync(data);
        const name = file.replace(".zip", "");
        resolve(await zip.file(name).async('text'));
      } catch(error) {
<script>/*IGNORE*/const JSZipUtils = {getBinaryContent:(p,c)=>errs.gbc?c(new Error('gbc'),null):c(null,{foo:true})};const JSZip = {loadAsync:(d)=> Error('la')):({file:n=>({async:a=>errs.a?Promise.reject(new Error('a')):Promise.resolve('Hello World')})})};const errs = {gbc:false,la:false,a:false};/*IGNORE*/</script>

Javascript make asynchronous calls inside a loop and pause /block , We need to make a request to fetch info for each user and call our render method after all user data has been retrieved. The requests can be� If you do find that you need to invoke an asynchronous method and “block” waiting for it (to satisfy a synchronous contract), and if that method marshals back to the current thread, and if changing the method’s implementation won’t work (e.g. because you don’t have the ability to modify it), and if offloading won’t work (e.g

This kind of sounds like a use case for async iterator generators, but maybe I'm just over-engineering. You have a bunch of resources that you want to iterate over and their contents are asynchronous. You want it to "look" synchronous, so you can leverage async/await:

function getZip(zipFile) {
   * Theres no point in simplifying this function since it looks like
   * the JSZip API deals with callbacks and not Promises.
  return Promise.resolve(zipFile);

function someFn(a, b) {
  return `${a}: ${b.length}`;

async function* zipper(elements) {
  for (const element of elements) {
    for (const data of element) {
      const txt = await getZip(data);
      yield someFn(txt, data);

(async() => {
  const elements = [
  let total = [];
  for await (const out of zipper(elements)) {

JavaScript Promises and Async/Await: As Fast As Possible™, Since we have a setTimeout call in the executor function which contains resolve call, it will execute when all asynchronous code is executed. then� Nested do-while loop. A do-while loop inside another do-while loop is called nested do-while loop. For example: do { // body of outer while loop do { // body of inner while loop } while (condition-2); // body of outer while loop } while (condition-1); Example 4: Nested do-while Loop

Using Promises, Modern functions return a promise that you can attach your callbacks to before the completion of the current run of the JavaScript event loop. Each callback is executed one after another, in the order in which Promise.resolve() and Promise.reject() are shortcuts to manually create an already resolved� This loop includes for loop, while loop, do while loop. Let's go for example. Consider about the loop below. It will be traversed for 10 times and print the number-0123456789 one after another. Each time it would display one number and after traversing the loop for the subsequent time, it would display the subsequent number and proceed thereby.

Graceful asynchronous programming with Promises, One of the most common engagements you'll have with promises is with web to be called multiple times (once for each nested function), with other Inside the executor function, we include a simple if else if statement to return a The executor will only run when all three promises resolve; when that� In this article, I will present a common case where loop and async function interact. The situation. I have to make a loop through an array, then with each item make an async data call and do some calculation with the index inside the callback function. A similar situation can be found below:

JavaScript: Promises and Why Async/Await Wins the Battle, The good side is that asynchronous functions are non-blocking and, as you sometimes have to wait for one function to complete in order to get its create promise with resolve and reject as params “callback hell”, which is really just a series of nested function calls. Increase engagement with feeds. Promises not only provides a simpler paradigm for composing chains of asynchronous processes, but also throws in tools for managing parallel processing. Chaining Promises In my previous column, I showed how to use the done method to perform processing when a Promise is resolved (that is, when the Promise returns its result).

  • could wrap the loop in an anonymous async function and await the promise, or in your loop push promises to array then call promise.all()