简体   繁体   中英

How to automatically wait until a function is done with promises in node.js/javascript?

I have a module that when instantiate it, it runs a lot of asynchronous functions.

var freader = new filesreader();    // <-- this runs a lot of async functions
var IMG_ARRAY = freader.get_IMG_ARRAY();   // <-- I get the array that stuff gets put into
console.log(IMG_ARRAY); // <-- this prints an empty array

When I create a new filesreader it, creates [] and then runs a lot of async code to put stuff in the array. Then I want to get the array and print it. But since theres async code, if I try to get the array in the next line and print it, it will be empty. I need to wait until all the async code has finished in the module, but theres so much stuff I don't want to manually track everything and put callbacks everywhere. Is there a way I canjust automatically wait until the function has finished fully through some hack?

Thanks

Rather than writing filesreader so it returns an array that will be populated, have it return a Promise:

function get_IMG_ARRAY() {
  var result = [];
  return new Promise(function (resolve, reject) {
    // All your async stuff, then eventually...
    resolve(result);
  });
}

That way, all you have to do to consume it is this:

var freader = new filesreader();
freader.get_IMG_ARRAY().then(function (IMG_ARRAY) {
  console.log(IMG_ARRAY);
}, function (err) {
  // Handle any errors
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM