繁体   English   中英

“异步”Azure 函数应用程序未按预期等待

[英]'async' Azure Function App not awaiting as expected

我正在尝试使用节点的 Azure 存储 SDK 在表格存储中创建一个表格(如果它不存在)。

以下代码有效,返回200响应,虽然没有响应内容。 但是,表是按预期创建的。

经过调查,我可以看到 Azure Function 应用程序正在记录以下内容 -

创建表“测试”。
[警告] 警告:函数执行完成后,意外调用上下文对象上的“日志”。 请检查未等待的异步调用或在函数执行完成之前调用“完成”。

因此,虽然createTableInTableStore按预期工作,但我的函数的 async/await 部分却没有。 我怀疑我做错了什么,但从它的外观来看,我正确地实现了await以及何时需要它。

如何让函数在继续之前等待createTableInTableStore方法完成?

示例代码

请注意 azure-storage npm 包是必需的( npm install azure-storage )。

module.exports = async function (context) {
    var azure_storage = require('azure-storage');
    var table_service = azure_storage.createTableService(process.env["AzureWebJobsStorage"]);
    var create_table_result = await createTableInTableStore(context, table_service, "Test");
    return {
        res: create_table_result
    };
};

async function createTableInTableStore(context, table_service, table_name) {
    context.log("Creating table '"+table_name+"'.");
    return await table_service.createTableIfNotExists(table_name, function(error, result, response) {
        if (!error && result) {
            context.log.info("[Info] Table created successfully.")
        } else if (!error && !result) {
            context.log.info("[Info] Table already exists.")
        }
        if (error) {
            context.log.error("[Error] An unexpected error occurred.")
            context.log.error(" -----> " + response)
        }
    });
}

你可以返回一个它会起作用的承诺。 并在使用 await 时使用 try catch 处理错误。

module.exports = async function (context) {
    try{
    var azure_storage = require('azure-storage');
    var table_service = azure_storage.createTableService(process.env["AzureWebJobsStorage"]);
    var create_table_result = await createTableInTableStore(context, table_service, "Test");
      return {
          res: create_table_result
      };
    }catch(err){
    //handle errr
    console.log(err);
     }
};

function createTableInTableStore(context, table_service, table_name) {
    context.log("Creating table '"+table_name+"'.");
    return new Promise((resolve, reject) => {
      table_service.createTableIfNotExists(table_name, function(error, result, response) {
        if (!error && result) {
            context.log.info("[Info] Table created successfully.")
            resolve(result)
        } else if (!error && !result) {
            context.log.info("[Info] Table already exists.")
            resolve(response)
        }
        if (error) {
            context.log.error("[Error] An unexpected error occurred.")
            context.log.error(" -----> " + response)
            reject(error)
        }
    });
});
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM