如何使用Promise等待导出模块

时间:2019-09-13 06:34:14

标签: node.js asynchronous es6-promise module.exports

基本上,我的Express应用程序设置中需要执行一些异步操作。我曾经在脚本的结尾处添加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);
});

它就像模块一样。exports从未被调用。

2 个答案:

答案 0 :(得分: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.

答案 1 :(得分: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
  })
}

注意:此代码示例不是真实代码。只是在这里,我试图为您提供有关问题的答案。