【问题标题】:Azure Mobile Server Script - Get column value from another tableAzure 移动服务器脚本 - 从另一个表中获取列值
【发布时间】:2014-02-11 13:19:44
【问题描述】:

我正在使用 Azure 移动服务。我有两个表,我想做的是从 TableA 中获取一个列值,当我在 TableB 上运行插入时,通过检查它与 TableB 中的列值匹配的位置。

我的插入服务器脚本如下:

function insert(item, user, request) {

    var TableA_Table = tables.getTable('TableA');

    tableA_Table
        .where({ columnValue: item.columnValue })
        .read ({ success: setItemColumnValue });

    request.execute();

    function setItemColumnValue(result)
    {
        item.tableA_id = result.id;
    }
}

我已经确认我的 tableA_Table.where 命令正在从 TableA 中提取正确的行,但是当我在 setItemColumnValue 函数中输入 console.log(result) 时,它会打印 undefined。

我找到的所有文档都显示了与我相似的代码,但我就是不知道哪里出错了。 任何帮助表示赞赏!

【问题讨论】:

    标签: azure azure-storage azure-mobile-services


    【解决方案1】:

    您的脚本中有几个问题。首先,你要记住的是表访问代码是异步的。发生的情况是该函数是回调函数“setItemColumnValue”仅在request.execute(); 之后被调用,这意味着该项目将在没有tableA_id 成员集的情况下插入。另一个问题是 read 成功回调返回 结果数组,而不是单个结果(就像 SQL SELECT FROM 语句一样),因此该数组没有 id字段 - 它的成员拥有它。尝试像下面的代码那样重写代码,这应该可以工作。

    function insert(item, user, request) {
    
        var TableA_Table = tables.getTable('TableA');
    
        tableA_Table
            .where({ columnValue: item.columnValue })
            .read ({ success: setItemColumnValue });
    
        function setItemColumnValue(results)
        {
            if (results.length === 0) {
                // what should it do if there is no matching on table A?
                // Assuming here that this is an error.
                request.respond(statusCodes.BAD_REQUEST, { error: 'No matching item in table A' });
            } else if (results.length === 1) {
                item.tableA_id = results[0].id;
                request.execute();
            } else {
                // what should it do if there are multiple matches on table A?
                // Assuming here that this is an error.
                request.respond(statusCodes.BAD_REQUEST, { error: 'Multiple matches in table A' });
            }
        }
    }
    

    【讨论】:

    • 谢谢卡洛斯!正如你所提到的,我已经更新了我的代码,我现在直接访问数组成员的 id 值,我现在了解了回调函数的异步性质。我剩下的唯一问题是 Azure 抛出“错误:不能多次调用执行”,即使我的第二个 request.execute 在我的 setItemColumnValue 函数中,正如你所布置的那样。有什么想法吗?
    • 抱歉,我忘记在read 调用之后删除对request.execute() 的调用。由于在读取回调中所有代码路径都会响应请求(通过调用request.respondrequest.execute),因此不再需要原始路径。我更新了答案中的代码。
    • 再次感谢卡洛斯,非常感谢。
    • 在你的回答中你有item.TableA_id = result.id,但由于结果是一个数组,它不应该是results[0].id吗?
    • @winnicki 你说得对,我刚刚用那个更新编辑了帖子。感谢您了解这一点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-06
    • 1970-01-01
    • 2011-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多