Unable to alter JSON variable within a function

半世苍凉 提交于 2019-12-25 18:59:20

问题


Altering a JSON variable is failing for following snippet:

var data = {status: ''};

rosconnection.setOnOpen(function (e) {
        data.status = 'Succeeded';
        alert('success');
});

rosconnection.setOnError(function (e) {
        data.status = 'Failed';
        alert('fail');
});

data stays empty, but the alert gets called within rosconnection.setOnOpen. The error is hard to replicate hence its used on a ros connection, but i am 100% certain that it enters atleast one of the functions with success.


回答1:


You didn't show us how you know the status didn't change so...

My bet is: there is no way you saw the alert without the data being changed so your code probably looks something like this:

var data = {status: ''};

rosconnection.setOnOpen(function (e) {
        data.status = 'Succeeded';
        alert('success');
});

rosconnection.setOnError(function (e) {
        data.status = 'Failed';
        alert('fail');
});

alert(data.status);

So the status was not set yet. Check it inside the callback. AJAX...
What does AJAX means? A is for async, which means it will fire sometime in the future(near or far), you can't know when and sometimes don't even if it will ever be called.

Updated version:

var data = {status: ''};

rosconnection.setOnOpen(function (e) {
        data.status = 'Succeeded';
        alert(data.status);
});

rosconnection.setOnError(function (e) {
        data.status = 'Failed';
        alert(data.status);
});


来源:https://stackoverflow.com/questions/14791021/unable-to-alter-json-variable-within-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!