'JavaScript promise .then() not waiting for first part to finish

I was having some problem with promise in JavaScript.

// global array
var heatmapData1 = [];

function drawmap(mapData){
   let promiseKey = Promise.all(
      //use geocode to get lat lng, set promise to return marker object. This part is working so I never post the code
   );

  var addedMarkers = promiseKey.then(
    markers => Promise.all(
      // add the marker object returned and plot one by one onto map
      markers.map(marker => addMarker(marker))
    )
  // after finish plotting, get the completed array then draw heatmap
  ).then(plotHeatmap(heatmapData1);
 }

function addMarker(marker) {
    // so far everything here printed out result so my geocode part is working
    console.log(marker['lat'] + marker['lng'] + marker['branchName'] + marker['address'] + marker['total']);

    //one by one add marker onto map

    // add the marker one by one into global heatmap array
    heatmapData1.push({latitude: marker['lat'], longitude: marker['lng']}); 
    console.log('done add');
}

function plotHeatmap(heatmapData1){    
    console.log('go in');
    for(var i = 0; i < heatmapData1.length; i++){
        console.log('PLOT ' + heatmapData1[i].latitude + ' ' + heatmapData1[i].longitude);
    }
}

The problem now is the plotHeapmap method never wait for addMarker() to finish before executing. I chained a .then() there but it does not seem to work.

Is there any way to enforce that the addedMarkers part finish executing first before executing the plotHeatmap? Because I am populating the parameter for plotHeatmap inside addMarkers(), therefore I need that part finish execute first.



Solution 1:[1]

Line ).then(plotHeatmap(heatmapData1); lacks ) right before the semicolon, but the problem is that plotHeatmap is executed immediately, I believe you need to write something like

).then(plotHeatmap);

to pass a function to then

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 cyberskunk