程序启动时,我正在与某些JS模块进行同步和加载问题。此错误仅在开头显示一次,然后一切正常,因此这是一个明显的同步问题。
代码:
//pyramid of doom
function initGame(){
initWorld(function(){
initPlayer(function(){
initBots(function(){
console.log("Game Loaded!");
update();
})
})
});
}
function initWorld(callback){
world.init(worldParams);
callback&&callback();
}
function initPlayer(callback){
player.init(scene,playerParams,world.getPhysicModel());
callback&&callback();
}
function initBots(callback){
bots.init(scene,botsParams,world.getPhysicModel());
callback&&callback();
}
function update() {
world.update(1/60);
player.update();
bots.update();
}
initGame();
以下是我遇到的错误。
Bots.js:112 Uncaught TypeError: Cannot read property 'mixer' of undefined
at Bots.update (Bots.js:112)
at update (Final.html:160)
我做错了什么?如何同步init函数的执行?
(我认为正在进行的是initbots的执行在udpdate函数开始运行之前没有到达它。)
您可以在我的存储库中找到(1)
的Bots.js模块答案 0 :(得分:2)
在bots.init
中执行new THREE.ColladaLoader().load
看起来是异步的。
在回调中,您填写了_bots
数组(self._bots[modelLoaded] = bot;
)。
但是,执行bots.init()
并且在执行initBots
函数回调之前不要等待这些异步调用完成。在initGame
执行的情况下,此回调会执行update()
,而bots.update()
会执行this._bots[i].mixer
,i
会尝试使用this._botsParams.length
索引_bots
来访问undefined
1}},即一个预定义的值,不考虑var keyPropertyName = typeof(TEntity).GetProperties()
.First(p => p.CustomAttributes.Any(ca => ca.AttributeType.Name == "KeyAttribute")).Name;
return _dbSet.OrderBy(keyPropertyName).Skip(skip).Take(take).ToList();
数组中实际填充了多少项。
因此您的错误消息:数组在某些索引处没有项目,并且尝试读取CORES=$(grep -c ^processor /proc/cpuinfo 2>/dev/null || sysctl -n hw.ncpu || echo "$NUMBER_OF_PROCESSORS")
上的属性会引发错误。
结论:常见的异步问题。
答案 1 :(得分:1)
您需要将回调传递给init函数。从简短的机器人代码猜测,他们不期待接收回调,因此您可能正在进行重建。
如果已经完成,你无法从外部判断异步函数!
相当于你正在做的事情:
let result = undefined
function takeTime () {
setTimeout(function() {
result = 'hello!'
}, 100)
}
function callback () {
console.log(result)
}
function run (callback) {
takeTime()
callback && callback()
}
run(callback) // undefined! takeTime has not finished yet
你需要做什么:
let result = undefined
function takeTime (callback) {
setTimeout(function() {
result = 'hello!'
callback()
}, 100)
}
function callback () {
console.log(result)
}
function run (callback) {
callback && takeTime(callback)
}
run(callback) // 'hello!', the callback was only called once the takeTime function completed