Javascript 开关箱可以';t在嵌套回调中计算对象属性
这个函数接收像{'status':'info'}这样的对象参数,但我无法在某些回调中访问它。它不应该像所有代码块的全局变量吗Javascript 开关箱可以';t在嵌套回调中计算对象属性,javascript,callback,Javascript,Callback,这个函数接收像{'status':'info'}这样的对象参数,但我无法在某些回调中访问它。它不应该像所有代码块的全局变量吗 var msg = { status: 'good', data: 'cats' }; function status(msg) { console.log(msg.status); doSomething(msg.data, function(err, reply) { doSomething2(reply, funct
var msg = {
status: 'good',
data: 'cats'
};
function status(msg) {
console.log(msg.status);
doSomething(msg.data, function(err, reply) {
doSomething2(reply, function(err, data) {
switch(msg.status) { // error: cannot get status of undefined
case 'info':
console.log('Cat info.');
}
});
});
}
function doSomething(data, cb) {
return 'burdz';
}
function doSomething2(data, cb) {
return data + ' and dogs';
}
status();
访问交换机案例中消息的对象属性时引发错误。我可以在doSomething函数之前访问属性,但不能在最后一个函数中访问属性。
const msg={
状态:“好”,
数据:“猫”
};
功能状态(msg){
控制台日志(消息状态);
doSomething(msg.data,函数(err,reply){
doSomething2(回复、功能(错误、数据){
开关(消息状态){
案例“信息”:
console.log('Cat info');
}
});
});
}
功能剂量测量(数据,cb){
返回“burdz”;
}
函数doSomething2(数据,cb){
返回数据+‘和狗’;
}
状态(msg)代码>最可能的情况是,变量被问题中未包含的某些代码覆盖。你需要提供一个使用承诺!!!