意外行为-IIFE 需要时异步等待?

Unexpected behavior - Async Await when required with IIFE?

我有两个 nodejs 文件,其中异步等待不起作用,如果我 require 一个节点模块 (test2.js)其中定义了 IIFE。

test1.js

async function abc() {
    console.log(1)
    let computeFunction = await require("./test2");
    console.log(4)
    computeFunction()
    return null;
}

(async () => { await abc() })()

test2.js

The idea here is to export a function which does some computations,
but before exporting, I need to initialize database connections so that the computation function will work properly.

function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

(async () => {
    console.log(2)
    // some connection initialization
    await sleep(1000)
    console.log(3)
    return null;
})()

module.exports = async () => {
    // does some computation with those connections
    console.log(5)
    return null;
}

输出

实际

1
2
4
5
3

预计

1
2
3
4
5

I figured other solution by not using IIFE, but I want to know why async-await won't work when requiring a module which has an IIFE

这里你用了 Promise() inside he async/await 。但 async/await 本身 returns 承诺的价值。查看我的代码并查看演示。

async function abc() {
  try {
    console.log(1)
    let computeFunction = await hey();
    console.log(4)
    return null;
  } catch (e) {}
}

(async function() {
  await abc()
})();


function sleep() {
  console.log("do some cool stuff"); //make your database connection . 
}

function hey() {
  try {
    (async() => {
      console.log(2)
      // some connection initialization
      await sleep()
      console.log(3)
      return true;
    })()
  } catch (e) {
    console.log(e);
  }
}

这是一个非常错误的说法async-await won't work when requiring a module which has an IIFE。 实际输出与预期输出不同是因为 synchronous nature of require 而不是因为 IIFE。

如果你使用任何异步require函数,你可以得到1,2,3(after waiting for 1000ms), 4 ,5顺序的输出。

检查这个:-

test1.js

const asyncRequire = require('./async-require');

async function abc() {
    console.log(1)
    let computeFunction = await asyncRequire("./test2.js");
    console.log(4)
    computeFunction()
    return null;
}

(async () => { await abc() })();

test2.js

function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

await (async () => {
    console.log(2)
    // some connection initialization
    await sleep(1000)
    console.log(3)
    return null;
})();

module.exports = async () => {
    // does some computation with those connections
    console.log(5)
    return null;
}

异步-require.js

const fs = require('fs');
module.exports = async path=>{
    return new Promise((success, fail)=>{
        fs.readFile(path, async (error, file)=>{
            const myModule = {};
            await eval(`(async (module)=>{ ${file.toString()} })(myModule);`);
            success(myModule.exports);
        }); 
    })
}