如何执行异步JavaScript设置器?

时间:2019-04-29 16:31:06

标签: javascript ecmascript-6 promise async-await

我正在尝试使用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函数的返回值似乎被忽略了。

我该怎么办?

2 个答案:

答案 0 :(得分:2)

赋值表达式始终在其右侧求值。

$subject_id = $_GET['subject_id'];

没有办法改变它。

答案 1 :(得分:0)

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

您在设置器中的代码实际上没有设置。如果这是实际的数据库调用,则可以在数据库中保存一些值,然后对getter的下一次调用将产生新值。如果将类似这样的内容添加到fan DB调用中,则将更接近于传统的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
})();