Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would one do async JavaScript setters?

I'm trying to do asynchronous setters using async/await keywords.

Here some fakes database functions that takes time

function getProjectFromDatabase() {
    return new Promise((resolve, reject) => {
        setTimeout(() => resolve('My cool project!'), 500) // 500ms latency
    });
}

function setProjectToDatabase(projectName) {
    return new Promise((resolve, reject) => {
        setTimeout(() => resolve('set!'), 500) // 500ms latency
    });
}


Here is an example of implementation for the user

let user = {

    // Getter
    get project() {
        return (async () => {
            return await getProjectFromDatabase();
        })();
    },

    // Setter
    set project(projectName) {
        return (async () => {
            return await setProjectToDatabase(projectName);
        })();
    },

    // Method 
    setProject(projectName) {
        return (async () => {
            return await setProjectToDatabase(projectName);
        })();
    }
};


And here is an example of use

(async function() {
    console.log(await user.project); // Getter works!
    await user.setProject('My new cool project!'); // Method works!
    await (user.project = 'Another project'); // Setter doesn't work...
})();


But the return value from the setter function seems ignored.

How could I do that?

like image 667
Sharkou Avatar asked Apr 17 '26 19:04

Sharkou


1 Answers

The assignment expression always evaluates to its right-hand side.

  a.b.c = "This is what it gets evaluated to"

there is no way to change that.

like image 191
Jonas Wilms Avatar answered Apr 20 '26 08:04

Jonas Wilms



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!