From cf4aa9c33a4548b6d3125fd5a7a45f9627f88692 Mon Sep 17 00:00:00 2001 From: didier amyot Date: Wed, 27 Sep 2023 16:53:49 -0400 Subject: [PATCH] added example --- src/asyncawait.ts | 57 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 src/asyncawait.ts diff --git a/src/asyncawait.ts b/src/asyncawait.ts new file mode 100644 index 0000000..e4c3770 --- /dev/null +++ b/src/asyncawait.ts @@ -0,0 +1,57 @@ +import { delay } from "https://deno.land/std@0.202.0/async/delay.ts"; + + +async function downloadFilesWithDelay(urls: string[]): Promise{ + let ret: string[] = []; + for(const url of urls){ + await delay(1000); + const resp = await fetch(url); + ret.push(await resp.text()); + } + return ret; +} + +async function downloadFile(): Promise { + const url = "https://didier-ahuntsic.gitlab.io/cours-420-317-ah/data/grades.json"; + const resp = await fetch(url); + const payload = await resp.json(); + let ser = JSON.stringify(payload); + await Deno.writeTextFile("grades.json", ser); +} + +type Index = {links: string[]}; + +async function getIndex(url: string): Promise{ + const resp = await fetch(url); + return (await resp.json()) as Index; +} + +async function getEachUrl(links: string[]): Promise { + const ret : string[] = []; + for(const url of links){ + const resp = await fetch(url); + ret.push(await resp.json()); + } + return ret; +} + +async function downloadSubUrls(url: string): Promise{ + const index = await getIndex(url); + return await getEachUrl(index.links); +} + +// const url = "https://didier-ahuntsic.gitlab.io/cours-420-317-ah/data/exo-index.json"; +// const ret = await downloadSubUrls(url); +// console.log(ret.length) + +async function download2InParallel():Promise{ + const url1 = "http://httpbin.org/delay/3"; + const url2 = "http://httpbin.org/delay/3"; + const pResp1 = fetch(url1); + const pResp2 = fetch(url2); + await Promise.all([pResp1, pResp2]); + +} + + +