处理来自异步函数的空响应的正确方法是什么?

What is the correct way to handle a null response from an asynchronous function?

我正在开发一个 Azure 函数,它与我的 table 通信并更新 table 中的数据。我最近发现 Microsoft.WindowsAzure.Storage 包现在只有 Async 功能,我对那些不熟悉。

在我用于测试的函数中,我想 return 如果该行存在则为 true,如果不存在则为 false。如果该行存在,它会工作,但如果该行不存在,程序就会挂起(因为它正在等待响应)。

谁能帮帮我?

这是我的代码:

public static bool rowExists(CloudTable table, string city, string state)
{
    TableOperation tOP = TableOperation.Retrieve<SickCity>(city, state);
    Task<TableResult> result = table.ExecuteAsync(tOP);
    if (result == null)
        return false;
    else
        return true;
}

编辑:

这是我调用 rowExists 的地方

log.Info($"Does the row \"New York, NY\" exist? {rowExists(sickTable, "New York", "NY")}");

您没有得到预期的结果,因为您的代码没有等待异步请求完成。您需要稍微更改一下函数才能正确调用 ExecuteAsync:

public static async Task<bool> rowExists(CloudTable table, string city, string state)
{
    TableOperation tOP = TableOperation.Retrieve<SickCity>(city, state);
    var result = await table.ExecuteAsync(tOP);

    if (result == null)
        return false;
    else
        return true;
}

ExecuteAsync returns a Task,直到将来某个时间(异步操作完成时)才会包含实际结果。 await 关键字将使您的代码在该行上 "pause" 并等待 ExecuteAsync 任务包含实际值。然后你的逻辑可以继续。

请注意,方法签名已更改:现在是 async Task<bool> rowExists。您的方法现在 returns 也是 Task,这意味着调用 this 方法的代码也必须使用 await。这是处理数据库和网络调用等异步操作的常见模式。

如果这看起来很奇怪,您可以在此处阅读有关 async/await 模式的更多信息: