Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
256 views
in Technique[技术] by (71.8m points)

javascript - Unable to alter JSON variable within a function

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...