Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Example for migrating from NodeJS (CommonJS) async/await to top-level await in Deno #1006

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions examples/await-commonjs.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/**
* @title Await: CommonJS
* @difficulty beginner
* @tags cli
* @resource {https://docs.deno.com/api/deno/~/Deno.readTextFile} Doc: Deno.readTextFile
* @group Basics
*
* Example of how top-level await can be used by default in Deno. This example would assist in migrating from NodeJS (CommonJS) to Deno.
*/

// File: ./node-await.ts

// This example is what you may be used to with NodeJS when using CommonJS modules.
// Notice that for "await" to be used in this example, it must be wrapped in an "async" function.
const fs = require("fs");

async function readFile() {
try {
const data = await fs.promises.readFile("example.txt", "utf8");
console.log(data);
} catch (err) {
console.error(err);
}
}

readFile();

// File: ./deno-await.ts

// This is the same example as above, but with Deno.
// Notice that as well as being able to use "await" outside of an "async" function, we can also make use of Deno's Filesystem API.
try {
const data = await Deno.readTextFile("example.txt");
console.log(data);
} catch (err) {
console.error(err);
}
Loading