javascript - wait for loop to finish first

21,907

Solution 1

What about using Promise?(ES6 Code)

function callback_Original(results, status) {
            return new Promise((resolve, reject) => {
                if (status === google.maps.places.PlacesServiceStatus.OK) {
                    for (var i = 0; i < results.length; i++) {
                        createMarker_Original(results[i]);
                    }
                    resolve();
                }else
                    reject("Places service error");
            });
        }

And then just use

callback_Original(a,b)
.then(response => {
// Loop finished, what to do nexT?
})
.catch(error => {
// Error
console.log(error);
});

Solution 2

use async, it'll wait for promise. Reference

function callback_Original_child(results, status) { 
    return new Promise(resolve => {
        if (status === google.maps.places.PlacesServiceStatus.OK) { 
          for (var i = 0; i < results.length; i++) { 
                createMarker_Original(results[i]);
          }
        }
    });
}

async function callback_Original(results, status) { 
    try {
        await callback_Original_child(results, status);
    } catch (error) {
        console.log(error);
    }
}

callback_Original()
Share:
21,907

Related videos on Youtube

MaeLstroms Stroms
Author by

MaeLstroms Stroms

Updated on July 09, 2022

Comments

  • MaeLstroms Stroms
    MaeLstroms Stroms over 1 year

    I want to finish first all results before going to another loops. How can I manage to achieve that?

    function callback_Original(results, status) { 
        if (status === google.maps.places.PlacesServiceStatus.OK) { 
          for (var i = 0; i < results.length; i++) { 
                    createMarker_Original(results[i]);
          }
        }
      }
    

    It always gives few places sometimes.

    function createMarker_Original(place) {
        var photos = place.photos;
        if (!photos) {
            return;
        }
    
        var placeLoc = place.geometry.location;
        var marker = new google.maps.Marker({
          map: map,
          position: place.geometry.location
        });
    
    
    
        google.maps.event.addListener(marker, 'click', function() { 
              infowindow.setContent('<div style="float:left"><img src="' + photos[0].getUrl({'maxWidth': 120, 'maxHeight': 120}) 
              + '"></div><div style="float:right; padding: 10px;"><b>Name: </b>'+  place.name +'<br/>'+
              '<b>Coordinates : </b>'+ place.geometry.location +'<br/>'+
              '<b>Type: </b>'+ type +'<br/>');
              infowindow.open(map, this);
        });
    }
    
    • Dai
      Dai about 6 years
      What does createMarker_Original do?
    • Dai
      Dai about 6 years
      Also, JavaScript in the browser is (for the most part) asynchronous - it does not block or wait - so if you're making an external HTTP request then, no, you cannot block or wait for it to finish - you have to structure your program around the concept of asynchronous-programming. It's the future: Node.js is entirely async, C# has await and C++ is getting something similar.
    • MaeLstroms Stroms
      MaeLstroms Stroms about 6 years
      Is there a way to do that? @Dai
    • Dai
      Dai about 6 years
      Yes, but we need to see the rest of your program in context.
    • MaeLstroms Stroms
      MaeLstroms Stroms about 6 years
      Update sir @dai
    • Roamer-1888
      Roamer-1888 about 6 years
      Creating markers and adding event listeners are both synchronous operations. The calling function should behave correctly with natural line by line flow. If you get fewer markers than expected, then results are incomplete.
  • Vipul Solanki
    Vipul Solanki about 6 years
    I'd updated my answer. for more detail go to reference. I have given.
  • Roamer-1888
    Roamer-1888 about 6 years
    If you accept that resolve() would be called when everything in the loop is complete, then it follows that createMarker_Original() is synchronous and the OP's original code would also work as he wants.