View a markdown version of this page

使用 async 和 await - Amazon CloudFront
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)。

使用 async 和 await

CloudFront Functions JavaScript 运行时函数 2.0 提供了 async 和 await 语法来处理 Promise 对象。Promise 表示延迟的结果,可以通过标记为 async 的函数中的 await 关键字进行访问。各种新的 WebCrypto 函数都使用 Promise。

有关 Promise 对象的更多信息,请参阅 Promise。

注意

对于以下代码示例,您必须使用 JavaScript 运行时 2.0。

await 只能在 async 函数内部使用。不支持 async 参数和闭包。

async function answer() { return 42; } // Note: async, await can be used only inside an async function. async arguments and closures are not supported. 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; }

以下 JavaScript 代码示例演示了如何使用 then 链式方法查看 Promise。您可以使用 catch 来查看错误。

警告

使用 Promise 组合器(例如 Promise.all、Promise.any)和 Promise 链方法(例如 then 和 catch)可能需要大量的函数内存使用量。如果您的函数超过了最大函数内存配额,它将无法执行。为避免出现此错误,建议您使用 await 语法,而不是 promise 方法。

async function answer() { return 42; } async function squared_answer() { return answer().then(value => value * value) } // Note: async, await can be used only inside an async function. async arguments and closures are not supported. 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; }