The 6 ways of returning data from an Azure Function

Why have one if you can have many? Well, beats me, but I thought I’d collect them here so I have my personal reference. Disclaimer: This is only for JavaScript based functions (most of the examples on the MS pages are C#).

So, most of them have to do with the file function.json  file:

More precisely, with the “out” type binding that is defined in the 2nd “bindings” object. The “out” binding has a “name” property, which is basically relevant for all of the methods.

Method 1 – context property

The context object has one property per defined “out” binding. So if our property is named “ this_is_an_out_binding “, our result property is context.this_is_an_out_binding , or as MicroSoft puts it:

Outputs (bindings of direction === "out" ) can be written to by a function in a number of ways. In all cases, the name property of the binding as defined in function.json corresponds to the name of the object member written to in your function.

Simply put, you just assign the value to a context  member and you’re done:

Source here.

Method 2 – return an object (async functions only)

With the bindings given above, you can assign the values to the context property, but you can also return an object whose keys correspond to the binding names:

Source here.

Method 3 – using context.bindings

This is basically a variant of method 1. Why does it exist? No one knows. Apparently the context object has a .bindings  property, which in turn again has properties which name-match the defined out bindings. So this is another possibility, and I think the return  is unnecessary:

Source here.

Method 4 – using context.done()

If you’re using a sync method, you can’t return an object, but you can call context.done(err, obj) .

Source here.

Method 5 – just return it already (only async functions)

Probably someone said “Well, if I only have one output binding, why should I explicitly address it?”, which is a valid thought. So another way to return data was invented.

For this the configuration in function.json looks a bit different:

You have to set exactly one “out” type binding, and the name must be “$return”. Then you can do this:

Source here.

Methods 6 – special for http outputs

You thought we were done? Noooooo. For http methods, you can diretly return the body object which is then used to create the body

Source here.

Summary

Let’s just say it’s a mess, and too many ways ruin the map.

It works though.