简体   繁体   中英

Modify global variable from ajax request

I know this has been asked countless times, but i can't figure out the problem. As far as i know, you can modify global variables inside functions in javascript. It doesn't work for me.

var lastMessage = 0;
function loadChat() {
$.post("/lastmessage", { roomid: roomId })
    .done(function(data) {
        var response = JSON.parse(data);
        if (response.state == "success") {
            lastMessage = response.message;
            console.log("Inside: " + lastMessage);
        }
    });
}

console.log("Outside: " + lastMessage);

This gives me

Outside: 0
Inside: 17

The inside value is correct, the outside is not. What could the problem possibly be?

It's asynchronous, therefore when you call it from outside, it has not finished executing yet. What this means is that this part of your code is only reached once the post has completed

.done(function(data) {
        var response = JSON.parse(data);
        if (response.state == "success") {
            lastMessage = response.message;
            console.log("Inside: " + lastMessage);
        }
    });

but console.log("Outside: " + lastMessage); will continue executing without waiting, since post is asynchronous.

If you want something to happen after you retrieve the value you, one option would be to use a callback function, such as:

function printMessage(message) {
    console.log(message)
}

function loadChat(callback) {
$.post("/lastmessage", { roomid: roomId })
    .done(function(data) {
        var response = JSON.parse(data);
        if (response.state == "success") {
            lastMessage = response.message;
            callback(lastMessage);
        }
    });
}

loadChat(printMessage);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM