1

There are two files, t1.js and t2.js, which are run using the command line.

$ node t2.js
f2
f1

# I want to output f1 f2, not f2 f1

I tried using async/await to solve the problem, but I didn't find a way to use it, and runMain() could not take any parameters.

document content

t1.js:

const f1 = new Promise(async resolve => {
  setTimeout(() => resolve('f1'), 1000)
})
new Promise(async () => {
  console.log(await f1)
})

t2.js:

new Promise(async () => {
  const t1Path = __dirname + '/t1.js'
  process.argv = [process.argv[0], t1Path]
  require('module').runMain()
  // await require('module').runMain() // This is invalid
  console.log('f2')
})
Ace
  • 11
  • 3
  • What is `require('module')`? Where is `runMain` declared? – Bergi Dec 14 '19 at 14:09
  • 1
    Btw, [never pass an `async function` as the executor to `new Promise`](https://stackoverflow.com/q/43036229/1048572)! – Bergi Dec 14 '19 at 14:12
  • 1
    I understand this trick from npx code: https://github.com/zkat/npx/blob/b7c8b9f07605b9f41931ad3ef8e74a65d2f062bb/index.js#L268 – Ace Dec 14 '19 at 14:14
  • @Bergi I think this is about Node, so that's the built-in Node synchronous module loader. I guess `runMain()` is an exported function from the module being loaded. – Pointy Dec 14 '19 at 14:17
  • 2
    This seems to be an [xy problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Why do you need this in the first place? Why not have a proper `export` and use it the regular way? –  Dec 14 '19 at 14:19
  • @Ace the comment in that code you link suggests that it's doing something fishy, and indeed that `.runMain()` method is not documented. – Pointy Dec 14 '19 at 14:21
  • @Pointy Oh, I had not known about [that `module` builtin](https://nodejs.org/api/modules.html#modules_the_module_object_1)! (And the [same-named npm package](https://www.npmjs.com/package/module) is totally unrelated) – Bergi Dec 14 '19 at 14:27
  • @ChrisG t1.js can be anyone's js code, t2.js just wants to run it directly. The author of t2.js does not write t1.js code. – Ace Dec 14 '19 at 14:35
  • 1
    Well the bottom line is that `require()` is synchronous. The Promise and `async` functions you've written don't change anything because the function passed to `new Promise()` is invoked immediately (synchronously); making it an `async` function doesn't change that. – Pointy Dec 14 '19 at 14:37
  • Thank you for letting me know that I asked a wrong question. From the second Promise code in t1.js, there is no resolve, t2.js never knows when its execution is complete. – Ace Dec 14 '19 at 14:45

0 Answers0