Use async and await - Amazon CloudFront

Use async and await

CloudFront Functions JavaScript runtime functions 2.0 provide async and await syntax to handle Promise objects. Promises represent delayed results that can be accessed via the await keyword in functions marked as async. Various new WebCrypto functions use Promises.

For more information about Promise objects, see Promise.

Note

You must use JavaScript runtime 2.0 for the following code samples.

async function answer() { return 42; } // Note: async, await can be used only inside an async function. async function handler(event) { // var answer_value = answer(); // returns Promise, not a 42 value let answer_value = await answer(); // resolves Promise, 42 console.log("Answer"+answer_value); event.request.headers['answer'] = { value : ""+answer_value }; return event.request; }

The following example JavaScript code shows how to view promises with the then chain method. You can use catch to view errors.

async function answer() { return 42; } async function squared_answer() { return answer().then(value => value * value) } // note async, await can be used only inside async function async function handler(event) { // var answer_value = answer(); // returns Promise, not a 42 value let answer_value = await squared_answer(); // resolves Promise, 42 console.log("Answer"+answer_value); event.request.headers['answer'] = { value : ""+answer_value }; return event.request; }