我调用called.js
来处理给定的数组。完成需要一段未知的时间。我希望在继续called.js
中的主序列之前确保处理完成。
在主模块继续执行之前,如何确保处理完成?
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
});
}
};
修复
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);
}
答案 0 :(得分:0)
您可以使用回调(如bergi告诉):
向普通的js添加一个函数:
function loaded(){
alert("loaded");
}
添加已加载的js insert的结尾:
loaded();