31

There are wiki articles about them: (http://en.wikipedia.org/wiki/Futures_and_promises, http://en.wikipedia.org/wiki/Thunk_(delayed_computation)). But I am not sure what are the exact differences between the three as a programming language concept? Are futures and promises only applicable in concurrent programming?

JRR
  • 6,014
  • 6
  • 39
  • 59

4 Answers4

15

An example of each, using javascript since everybody can read it.

Please don't use this code in production, use a real library, there are plenty of good ones.

var a, b, c, async_obj;  // assume exist

// CommonJS - for reference purposes

try {

  async_obj.asyncMethod(a, b, c, function (error1, result1) {

    if (error1) {
      console.error(error1);
    } else {
      console.log(result1);
    }

  });

} catch (ex1) {
  console.error(ex1);
}

// Thunk - "a parameterless closure created to prevent the evaluation of an expression until forced at a later time"

function makeThunkForAsyncMethod (cb) {
  return function () {
    async_obj.asyncMethod(a, b, c, cb);
  }
}

var my_thunk = makeThunkForAsyncMethod(function (error1, result1) {
  if (error1) {
    console.error(error1);
  } else {
    console.log(result1);
  }
});

setTimeout(function () {
  try {
    my_thunk();
  } catch (ex1) {
    console.error(ex1);
  }
}, 5e3);


// Promise - "a writable, single assignment container which sets the value of the future"

function makePromiseForAsyncMethod () {
  var
    future_then_cb,
    future_catch_cb,
    future
  ;

  future = {
    then: function (cb) {
      future_then_cb = cb;
    },
    catch: function (cb) {
      future_catch_cb = cb;
    };
  };

  try {
    async_obj.asyncMethod(a, b, c, function (error1, result1) {
      if (error1) {
        if (future_catch_cb) {
          future_catch_cb(error1)
        }
      } else {
        if (future_then_cb) {
          future_then_cb(result1);
        }
      }
    });
  } catch (ex1) {
    setTimeout(function () {
      if (future_catch_cb) {
        future_catch_cb(ex1);
      }
    });
  }

  return future;
}

// Future - "a read-only placeholder view of a variable"

var my_future = makePromiseForAsyncMethod();

my_future
  .then(function (result) {
    console.log(result);
  })
  .catch(function (error) {
    console.error(error);
  })
;

A Promise chain would be like the above contrived example, but it would work on collections and be more robust.

slf
  • 22,595
  • 11
  • 77
  • 101
13

in functional programming, the most difference between thunk and promise is, thunk is pure while promise is impure.

function thunkDemo() {
  return function(callback) {
    asyncMethod(someParameter, callback);
  };
}

function promiseDemo() {
  return new Promise(function(resolve, reject) {
     asyncMethod(someParameter, function(err, data) {
        if(err) return reject(err);
        resolve(data);
     });
  });
}

when thunkDemo is called, the asyncMethod will not be called until the inner method called, so thunkDemo is pure with no side affect.

when promiseDemo is called, it will call asyncMethod immediatly, which means, it's not pure.

Sean
  • 2,990
  • 1
  • 21
  • 31
3

Thunk is a general concept of a small function which is used only to adapt the call or prepare/modify it in some way and then redirect to the proper function. Things like promises, futures, closures, wrappers, stubs or implementations of the concept of virtual function tables in some OO languages (like C++) are just special use cases of thunks (thunks are often used to implement them).

SasQ
  • 14,009
  • 7
  • 43
  • 43
3

These are quite broad terms, and their usage and interpretations vary with context. So a specific answer can only be given for a specific context.

In javascript promise libraries for example, the terms "deferred" and "promise" are used for what your linked wiki article refers to as "promise" and "future" respectively, in that a "deferred" is the interface for resolving or rejecting the value, and "promise" is the interface for reading it, with some more specifics that allow easily constructing new promises for dependent values, but not actually changing the original promise.

I just stumbled upon the JS library "co" (https://github.com/visionmedia/co). It was the first time I heard of "thunks", and it seems to be using the term in a slightly different sense from slf's answer, and much more specific than your linked wiki as well. It is not a parameterless function that returns the value, it is a function accepting a callback that will call the callback with the value, often asynchronously.

In this specific library's case, thunks and promises are very close to each other: a promise is an object with a "then" method function that sets a callback for getting the value; a thunk is directly a function that sets a callback for getting the value.

user2451227
  • 463
  • 5
  • 9