模式:如何从异步函数返回的结果中正确访问object.properties

时间:2019-06-16 23:06:40

标签: javascript error-handling webstorm

我有一个函数,可以从数据库或API点fetch指向数据并为其添加属性,如下所示:

async function function_one (arg) {
    try {
        if (arg != number) throw new Error('error')
        let data = await findOne(arg);
        data['property'] = 1+2+3
        ....
        return data //this is an object with it's own properties
    } catch (e) {
        console.log(e); //errorHandling with winston
    }
}

和另一个(主)函数,这些函数使用以前功能的数据:

async function Master (user_input) {
    try {
        let object = await function_one(user_input);
        console.log(object.property_one) //weak warning
        let another_object = await another_function (fixed_arg);
        //some other logic with object properties.
        return result_data
    } catch (e) {
        console.log(e);
    }
}

因此,当我尝试访问object函数中的Master属性时,例如:

let object = await function_one(user_input);
console.log(object.property_one)

我的IDE(WebStrom)显示如下内容:enter image description here,但我知道如果function_one将正确执行(不包含catch块),则此属性将存在。并且,如果Master函数失败,则用户将不会收到来自function_one的消息。 (IDE说throw异常是在本地捕获的。)

那么我在做什么错了,我该怎么办?像这样处理Master函数中的每个异步函数:

async function Master (user_input) {
    try {
        let object = await function_one(user_input)
            .then(data => {
                //working with properties here and then return it?
            })
            .catch(error => {//handle it});

或从function_one返回所有属性,例如:return {property_one, property_two, ... }

1 个答案:

答案 0 :(得分:0)

使用destructuring assignment可以解决此问题