-1

基本上,我在快速应用程序的设置中需要一些异步操作。我曾经module.export = app在脚本的最后包含,但它不会在异步函数中包含这些内容,因为它们在到达该行之后结束。

我放置了一个名为 wait 的计数器,当它等于 0 时应该意味着所有异步函数都已完成。

我尝试将它放入一个循环中,并在一个 Promise 中放入一个循环,但没有任何效果

wait = 1;
()=>{
    //async function
    wait--;
}

module.exports = new Promise(function(resolve, reject) {
    console.log('hi', wait)
    setInterval(function () {
        if (wait == 0) {
            console.log('everything is done loading');
            resolve(app);
        }

        else console.log('...');
    }, 500);
});

它就像从未调用过 module.exports 一样。

4

2 回答 2

1

我的做法是这样的。这是我的 index.js 文件。

const app = require('express')();
const stuff1 = async () => {};
const stuff2 = async () => {};
const startServer = async ()=> {};
const init = async () => {
 await stuff1();
 await stuff2();
 // some other async or sync stuffs to do before i start my server
 await startServer();
}

init(); // process will exit if failed.
于 2019-09-13T06:48:46.543 回答
0

我认为您正在尝试将代码写入另一个文件夹,然后您正在导出,同时您期望返回值应该是承诺的方式。如果是,那么这可能会对您有所帮助

  //index.js
    async (req, res) => {
    await waitingFunction(req.body)
    then(data => {console.log(data)})
    .catch(error => {console.log(Error)})
}

接下来,您要从需要导出函数的位置创建文件

// export_file.js
exports.waitingFunction = async body => {
 new Promise((res, rej) => {
   // do your stuff if it gives error then return you error as below
   if(err) rej(err)
   else res(result)  // this if not error
  })
}

注意:此代码示例不是真正的代码。就在这里,我试图回答您的问题。

于 2019-09-13T07:05:25.040 回答