简体   繁体   中英

Javascript - How to make sure processing is finished in a remote module?

I call called.js which processes a given array. It takes an unknown length of time to complete. I want to make sure processing is complete before I continue the main sequence in called.js .

How do I ensure processing is complete before my main module continues execution?

caller.js

//caller.js
var called = require('./called.js');
var inst = new called();
var ary = [1, 2, 3];

console.log('caller before',ary);
inst.process(ary);
console.log('caller after',ary);
//do other stuff with the modified array

called.js

//called.js
module.exports = function () {
    var array = [];
    var a = 'a';
    var b = 'b';

    return {
        process: (arr)=> {
          array=arr;
          longtime();
        }
    };

    function longtime(){
        {para_a: a, para_b: b},
        function(err, response) {
              //process the response and update the array
              //takes an unknown time to complete,
              //and the number of elements to be updated are unknown also
        });
    }
};

The Fix

caller2.js

var called = require('./called.js');
var inst = new called();
var ary = [0, 1, 2];

console.log('caller before',ary);
inst.process(ary, do_work);

function do_work(){
  console.log('processing finished');
  console.log('caller after',ary);
}

called2.js

module.exports = function () {
var array = [];

return {
    process: (arr, callback)=> {
      array=arr;
      console.log('process calling longtime');
      longtime(array, function (response){
        console.log('process got callback:',response);
        callback();
      });
    }
  };
};

function longtime (ar, callback){
    setTimeout(function(){ //this simulates a slow API call
      ar.push(3);
      var str = 'array now '+ar.length;
      callback(str);
      }, 5000);
}

You could use a callback (like bergi told):

Add a function to your normal js:

function loaded(){
alert("loaded");
}

Add the end of the loaded js insert:

loaded();

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