await-top is a library that lets you use top-level await. Don't believe me? Have an example:
// test.js
require = require ( './index' )
console.log (
'Promise: %O',
require (
'./test-2',
module
).then (
( x ) => {
console.log ( x )
}
)
)// test-2.js
let fs = require ( 'fs' )
console.log ( await Promise.resolve ( 'Hello, World! (await from inside module)' ) )
module.exports = 'Hello, World! (exports)'
console.log (
'Contents of test.js:\n%s',
await new Promise (
(
accept,
reject
) => {
fs.readFile (
__dirname + '/test.js',
'utf8',
(
err,
data
) => {
if ( err ) {
reject ( err )
} else {
accept ( data )
}
}
)
}
)
)Output:
Promise: Promise { <pending> }
Hello, World! (await from inside module)
Contents of test.js:
require = require ( './index' )
console.log (
'Promise: %O',
require (
'./test-2',
module
).then (
( x ) => {
console.log ( x )
}
)
)
Hello, World! (exports)
In fact, that exact code is used for npm test. Note that the exports are printed after awaiting the filesystem call, because the Promise does not resolve until after the function has executed.
There is some important differences about await-top that make it different from other modules.
-
This does not apply globally. You can use regular
requirealongside this module and Node will not complain.await-topis very careful to clean up any changes it makes.The recommended way to use
await-top, however, is:require = require('await-top')
-
You must pass
moduletoawait-top'srequire. This is done to make sure the module resolves to a.jsfile so nothing unexpected happens, such as the_extensionsfunction never getting called and the next module imported getting async instead, screwing up the system. -
await-top'srequirereturns aPromise. You can use.then()orawaitit (inside a real async function). -
This module depends heavily on the internal structure of the module-loading system. Specifically, the call signatures of
Module._resolveFilename,Module.wrap,Module._compile, and the format ofModule._extensions. You can read how therequire()system works atloader.jsandhelpers.js.