I want to wait until the callback function finishes.

Asked 1 years ago, Updated 1 years ago, 34 views

I am developing an Android app in monaca.

I am creating a program that retrieves the update date of multiple files in a folder. As the callback works asynchronously, I would like to make sure that each callback is handled one by one.
Is it possible to wait for the callback to complete?

Thank you for your cooperation.

for(var index=0;index<fileEntries.length;index++){
  letentry=fileEntries [index];
  // For now, only .apk files are covered.
  let name=entry.name.toLowerCase();
  if(name.indexOf('.apk')!=-1){
    // I want to wait until this process is completed!!!
    entry.getMetadata(getMetadataSuccess,fail);
  }
}

function getMetadataSuccess(metadata){
  // alert("modificationTime:" + moment(String(metadata_datetime.toLocaleString())).format('YYYY/MM/DD HH:mm:ss'));
}

javascript monaca

2022-09-30 13:46

2 Answers

Entry.getMetadata is an asynchronous function, so it might work if you add wait to the beginning.Even so, you will need to create the main function as an asnyc function and rotate the for loop as shown in (B) below.

I wrote a sample using a mechanism called promise and async/await.You can now take asynchronous processing like synchronous processing.
The code that returns promise to the return value will be ready for wait.

Programming related to asynchronous processing is more difficult than programming of normal synchronous processing, so it is recommended that you learn and write a lot while moving samples.
Please understand by looking at and learning from various samples of Promise and async/await.

I also wrote it while checking the operation.

(A) Those that use setTimeout to simulate asynchronous processing and move separately
https://jsbin.com/fedisameje/edit?js,console

(B) Promise and async/await to synchronize asynchronous processing using setTimeout
https://jsbin.com/pekuvayezo/edit?js,console

(A)

constandomInt=(min,max)=>{
  return Math.floor(Math.random()*(max+1-min))+min;
};

constry_getMetadata=(i,name)=>{
  const interval = randomInt(1,10);
  setTimeout(()=>{
    console.log(`entry_getMetadata name:${name} index:${i}interval:${interval}`)
  }, interval);
};

const fileEntries = [
  {name: 'test1.txt'},
  {name: 'test2.apk'},
  {name: 'test3.apk'},
  {name: 'test4.apk'},
  {name: 'test5.apk'},
  {name: 'test6.apk',
  {name: 'test7.apk'},
];

for (var index=0; index<fileEntries.length;index++) {
  letentry=fileEntries [index];
  let name=entry.name.toLowerCase();
  if(name.indexOf('.apk')!==-1){
    entry_getMetadata (index, name);
  }
}

// console
// " entry_getMetadata name: test 5.apk index:4 interval:3"
// " entry_getMetadata name: test6.apk index:5 interval:4"
// " entry_getMetadata name: test3.apk index:2 interval:8"
// " entry_getMetadata name: test4.apk index:3 interval:9"
// " entry_getMetadata name: test2.apk index:1 interval:10"
// " entry_getMetadata name: test 7.apk index: 6 interval: 10"
// The order of execution is broken because interval is random number specification.

(B)

constandomInt=(min,max)=>{
  return Math.floor(Math.random()*(max+1-min))+min;
};

constry_getMetadata=(i,name)=>{
  const interval = randomInt(1,10);
  
  return new Promise ((resolve)=>{ 
      setTimeout(()=>{ 
        console.log(`entry_getMetadata name:${name} index:${i}interval:${interval}`);
        resolve();
      }, interval)
    })
};

const fileEntries = [
  {name: 'test1.txt'},
  {name: 'test2.apk'},
  {name: 'test3.apk'},
  {name: 'test4.apk'},
  {name: 'test5.apk'},
  {name: 'test6.apk',
  {name: 'test7.apk'},
];

constmain=async()=>{
  for (var index=0; index<fileEntries.length;index++) {
    letentry=fileEntries [index];
    let name=entry.name.toLowerCase();
    if(name.indexOf('.apk')!==-1){
      wait entry_getMetadata(index,name);
    }
  }
}

main();

// console
// " entry_getMetadata name: test2.apk index:1 interval:7"
// " entry_getMetadata name: test3.apk index:2 interval:9"
// " entry_getMetadata name: test4.apk index:3 interval:5"
// " entry_getMetadata name: test 5.apk index:4 interval:10"
// " entry_getMetadata name: test6.apk index:5 interval:1"
// " entry_getMetadata name: test7.apk index: 6 interval:1"
// Even if the interval is random, it waits for processing one by one.
// The order of processing is always in the order of execution.


2022-09-30 13:46

You can create Promise and wait at Promise.allSetted().

let promises=[];

for (var index=0; index<fileEntries.length;index++) {
  letentry=fileEntries [index];
  // For now, only .apk files are covered.
  let name=entry.name.toLowerCase();
  if(name.indexOf('.apk')!=-1){
    // I want to wait until this process is completed!!!
    let promote = new Promise ((resolve, reject) = > {
        entry.getMetadata(resolve, reject);
    });
    promote.push(promise);
  }
}

Promise.allSetted(promises).then(metadataArray=>{
    // Continue here.metadataArray is an array of metadata
});


2022-09-30 13:46

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.