Why Future Methods returns only void type?

Future methods will run in the future. You don't want your synchronous code waiting an unknown period of time for an asynchronous bit of code to finish working.

The whole point is you want to clearly separate what happens now from what happens in the future.

By only returning void, you can't have code that waits for a result.

It's also why you can only pass Ids and primitives as parameters. It's assumed the future method will execute at an unknown time in the future, so if you need database records you'll need to re-query the data to ensure it's fresh.


(I can't add a comment under Nick as my rep is low, but...)

To add to Nick Cook's answer,

There is a relatively new interface in Salesforce (Oct '14?), Queueable, which works the same as @future. That is, the platform queues up a process when the line of code is executed, and runs it at a later time in a separate execution.

Some key differences, and reasons why you should know about Queueable as well as @future -

  • A queueable process can queue another queueable, or launch an @future. Future methods cannot call future methods
  • Future methods can queue queueables
  • You can pass in non-primitive data types when you create a queueable object

This can be useful for either of the following -

  1. You need to recreate some multi-step process - for example, something that may require a rolling refresh through the UI, as a non-UI process
  2. You need a stateful queued process. For example, you can construct a queueable with your current controller and when the queued process starts, it already has the state of the controller at the time you queued the process

Here's more info about Queueables: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_queueing_jobs.htm

Note: With a little Apex Magic, you could have a future handler class which delegates between @future and Queueable, and using this class you can always make a callouut or queue another future process. As far as I can see, this requires that you pass information as primitive data.

Note2: Queueable itself is not always able to make callouts, so to fully leverage, you'll need both Queueables and @futures.

Tags:

Apex