1

I have the following task chain, where I want to access the variable decoder in the last task, but created in a much earlier task.

create_task(file->OpenReadAsync()).then([](IRandomAccessStream^ inStream) {
    return BitmapDecoder::CreateAsync(inStream);

}).then([localFolder](BitmapDecoder^ decoder) {
    return localFolder->CreateFileAsync("map.png", CreationCollisionOption::ReplaceExisting);

}).then([](StorageFile^ outFile) {
    return outFile->OpenAsync(FileAccessMode::ReadWrite);

}).then([](IRandomAccessStream^ outFileStream) {
    return BitmapEncoder::CreateAsync(BitmapEncoder::PngEncoderId, outFileStream);

}).then([](BitmapEncoder^ encoder) {
    BitmapPixelFormat pixelFormat = decoder->BitmapPixelFormat; // how do I make decoder available here?
    // Do stuff that uses encoder & decoder
});
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
Curyous
  • 8,716
  • 15
  • 58
  • 83
  • 3
    1. That hurts my eyes, and 2. that's not C++, it's C++/CLI – Ed S. Dec 09 '12 at 20:53
  • Any suggestions on how to make it less hurtful to your eyes? – Curyous Dec 09 '12 at 20:57
  • what do you think your benefit is to chain it like that? why not put all in one function and call that function in a task instead? – esskar Dec 09 '12 at 22:26
  • They are asynchronous operations with no equivalent synchronous functions, and I thought that it was best practice to chain the tasks rather than nest them. – Curyous Dec 09 '12 at 23:10
  • 1
    Girls-gone-wild code to the C++ crowd and Ed, it is C++/CX code. Which does not prevent you from storing an intermediate value in a field of your class so you can access it *later*. – Hans Passant Dec 09 '12 at 23:13
  • See also [How do I access previous promise results in a .then() chain?](http://stackoverflow.com/q/28250680/1048572) for the JavaScript equivalent – Bergi Jan 31 '15 at 10:58

1 Answers1

0

In the end I just assigned the variables I needed to variables local to the function that contained the task chain.

Curyous
  • 8,716
  • 15
  • 58
  • 83