首页 > 解决方案 > Azure 表存储返回查询结果

问题描述

我正在尝试创建一个 Azure 函数,该函数将接受参数并返回存储在 Azure 表中的值。我相信我遇到的问题与 javascript 的关系比与 Azure Table SDK 的关系更大。

您应该如何通过 http 响应从查询中返回值?我附上了代码的副本,它应该解释我在哪里感到困惑。我的主要困惑是由于我可以调用context.log()但无法context.res{}从查询方法中的函数调用。

我知道作用域与它有关,但我不是 javascript 和嵌套函数方面的专家。一些指导或示例将不胜感激

var azure = require('azure-storage');
module.exports = function (context, req) {
    context.log('Some Function');
    var hostUri = 'https://*******.table.core.windows.net'
    var sasToken = 'abc123'

    if (req.query.value) {
        var tableService = azure.createTableServiceWithSas(hostUri, sasToken)
        var nothing =  tableService.retrieveEntity('Table', 'Partition', 'Row', function(error, result, response) {
            if (!error) {
                context.log('I am able to send data to the logs here')         
                context.res = {
                    status: 200,
                    body: "This is what I am tring to return -> " + JSON.stringify(result) 
                };       
            }
        })
        context.res = {
            status: 200,
            body: "I'm able to get a response here"
        };  
    }
    else {
        context.res = {
            status: 400,
            body: "Somthing went wrong..."
        };
    }
    context.done();
};

标签: javascriptazurecallbackazure-functionsazure-table-storage

解决方案


先解决办法:

if (req.query.value) {
    var tableService = azure.createTableServiceWithSas(hostUri, sasToken)
     tableService.retrieveEntity('Table', 'Partition', 'Row', function(error, result, response) {
        if (!error) {
            context.log('I am able to send data to the logs here')         
            context.res = {
                status: 200,
                body: "This is what I am tring to return -> " + JSON.stringify(result) 
            }; 
        }
        else{
            context.res = {
                status: 400,
                body: error
            };
        }
        context.done(); 
    })

}
else {
    context.res = {
        status: 400,
        body: "Value is empty"
    };
    context.done();
}

解释:

让我们将 context.res 依次标记为 c1 和 c2 以避免冗余。

你被回调函数抓住了。function(error, result, response){}在从远程服务器检索到实体(或发生错误)之前,不会执行回调。这个操作可能需要一些时间,程序在等待它完成的同时继续执行,这个模式被称为asynchronous

因此,回调中的代码片段 c1 不会立即执行,而是 c2 会立即执行。然后context.done();在检索到的实体之前运行(您会看到响应消息I'm able to get a response here),因此永远不会调用回调。

依赖回调结果的代码应该包含在回调中,以便在回调完成后准确执行。放入context.done();回调和其他部分以确保它不会提前运行。

还有一篇关于异步 JavaScript的博客供您参考。


推荐阅读