如何做异步JavaScript setter?

问题描述 投票:2回答:2

我正在尝试使用async / await关键字进行异步设置器。 这里有一些假货数据库功能需要时间

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

以下是用户实现的示例

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

这是一个使用的例子

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

但是setter函数的返回值似乎被忽略了。 我怎么能这样做?

javascript ecmascript-6 promise async-await
2个回答
2
投票

赋值表达式始终计算到其右侧。

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

没有办法改变这一点。


0
投票

通常情况下,setter会设置一些值,而您不关心返回值。在传统的对象中,这将是一些其他属性(可能不打算直接使用)。转换为类似DB的东西,setter会发布INSERT或UPDATE,并设置新值。

你在setter中的代码实际上并没有设置任何东西。如果这是一个实际的DB调用,您将在数据库中保存一些值,然后下一次调用getter将产生新值。如果在风扇数据库调用中添加类似这样的内容,您将获得更接近传统getter / setter逻辑的内容:

const a_user = {project: 'My cool project!'} // some fake db object

function getProjectFromDatabase() {
    return new Promise((resolve, reject) => {
        setTimeout(() => resolve(a_user.project), 500) // 500ms latency
    });
}

function setProjectToDatabase(projectName) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            a_user.project = projectName // actually set something
            resolve(a_user.project)      // caller of setter doesn't care about return value, but we still need to resolve so async works.
        }, 500) // 500ms latency
    });
}
let user = {

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

};

(async function() {
    console.log(await user.project); // Getter works!
    await (user.project = 'Another project'); // 
    console.log(await user.project); // new value has been set
})();
© www.soinside.com 2019 - 2024. All rights reserved.