Mercurial > hg > nginx-site
diff xml/ru/docs/njs/examples.xml @ 2799:24b379907b0f
Added async and await to njs Examples.
author | Yaroslav Zhuravlev <yar@nginx.com> |
---|---|
date | Fri, 19 Nov 2021 08:19:57 +0000 |
parents | bf641527bd3d |
children | 9eadb98ec770 |
line wrap: on
line diff
--- a/xml/ru/docs/njs/examples.xml +++ b/xml/ru/docs/njs/examples.xml @@ -9,7 +9,7 @@ <article name="Примеры использования" link="/ru/docs/njs/examples.html" lang="ru" - rev="20"> + rev="21"> <section id="summary"> @@ -224,30 +224,29 @@ location /api { <para> <path>http.js</path>: <example> -function set_keyval(r) { - r.subrequest('/api/7/http/keyvals/foo', +async function set_keyval(r) { + let res = await r.subrequest('/api/7/http/keyvals/foo', { method: 'POST', - body: JSON.stringify({ foo: 789, bar: "ss dd 00" })}, + body: JSON.stringify({ foo: 789, bar: "ss dd 00" })}); - function(res) { - if (res.status >= 300) { - r.return(res.status, res.responseBody); - return; - } - r.return(500); - }); + if (res.status >= 300) { + r.return(res.status, res.responseBody); + return; + } + + r.return(200); } -function version(r) { - r.subrequest('/api/7/nginx', { method: 'GET' }, function(res) { - if (res.status != 200) { - r.return(res.status); - return; - } +async function version(r) { + let res = await r.subrequest('/api/7/nginx', { method: 'GET' }); - var json = JSON.parse(res.responseBody); - r.return(200, json.version); - }); + if (res.status != 200) { + r.return(res.status); + return; + } + + var json = JSON.parse(res.responseBody); + r.return(200, json.version); } export default {set_keyval, version}; @@ -332,20 +331,23 @@ location /backend { <para> <path>http.js</path>: <example> -function content(r) { - r.subrequest('/auth') - .then(reply => JSON.parse(reply.responseBody)) - .then(response => { - if (!response['token']) { - throw new Error("token is not available"); - } - return reply['token']; - }) - .then(token => { - r.subrequest('/backend', `token=${token}`) - .then(reply => r.return(reply.status, reply.responseBody)); - }) - .catch(_ => r.return(500)); +async function content(r) { + try { + let reply = await r.subrequest('/auth'); + let response = JSON.parse(reply.responseBody); + let token = response['token']; + + if (!token) { + throw new Error("token is not available"); + } + + let backend_reply = await r.subrequest('/backend', `token=${token}`); + r.return(backend_reply.status, backend_reply.responseBody); + + } catch (e) { + r.error(e); + r.return(500); + } } export default {content};