我正在使用 cpprestsdk 开发 CLIENT SERVER 应用程序,它工作正常。现在我想使用协同程序提高我的代码的可读性(很多 .then() 方法)。使用 co_await 编译器(在 VC++2015 或 VC++2017 上)将在“继续”中重构代码,摆脱 .then 语句。我试图理解 co_await 是如何工作的,但实际上我并没有完全理解。一般来说,如果我有这样的任务和延续:
client1.request(methods::GET, addr).then([=](http_response response)
{
printf("Response status code %u returned.\n", response.status_code());
if (response.status_code() == status_codes::OK)
{
wstring output = response.extract_utf16string().get();
wcout << output << endl;
}
}).wait();
它变得容易
auto response = co_await client1.request(methods::GET, addr);
printf("Response status code %u returned.\n", response.status_code());
if (response.status_code() == status_codes::OK)
{ wstring output = response.extract_utf16string().get();
wcout << output << endl;
}
我现在的问题是当我有这样的情况时:
pplx::task UploadFileToHttpServerAsync()
{
using concurrency::streams::file_stream;
using concurrency::streams::basic_istream;
namespace some_namespace = web::http;
// Open stream to file.
wstring filePath = L"out.txt";
return file_stream<unsigned char>::open_istream(filePath).then([=](pplx::task<basic_istream<unsigned char>> previousTask)
{
try
{
auto fileStream = previousTask.get();
// Make HTTP request with the file stream as the body.
http_client client(XMLReader::data.URL);
return client.request(methods::POST, filePath, fileStream).then([fileStream](pplx::task<http_response> previousTask)
{
如果我有 return 语句,如何使用 co_await 重构我的代码?