0

I have a JavaScript function as follows. It first retrieve some number of measurepoints which are image locations. To retrieve the image, there is a getFile function which processes the image in the callback.

Now the issue is I wanted the last console.log to show that both the data and measurepoints length are the same. However, the data length shows 0.

How do I ensure that the for loop completes first before continuing to the code outside the for loop?

async retrieveMeasuredData() {

   let measurepoints = await DataService.getData();
   let data = [];


   for (let i=0; i<measurepoints.length; i++) {
     let item = measurepoints[i];

     DeviceService.getFile(item.data.value, bMap1 => {
       let blob = bMap1.slice(0, bMap1.size, "image/jpg");
       let blobUrl = 'original: \'' + URL.createObjectURL(blob) + '\'';
       console.log('image url: ' + blobUrl);
       data.push(blobUrl);
     });
   }

   console.log('data length: ' + data.length + ' measurepoints length: ' + measurepoints.length);

   this.setState({
     data: data
   });
}


Eugene
  • 1,013
  • 1
  • 22
  • 43
  • You can try using [Promise.then()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) and the `console.log` in [Promise.finally()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/finally) – Liang-Shih Lin Feb 06 '20 at 02:10
  • Thanks all, in the end i used Promise.all() :) – Eugene Feb 06 '20 at 09:11

0 Answers0