首页 > 解决方案 > 如何使用承诺等待导出模块

问题描述

基本上,我在快速应用程序的设置中需要一些异步操作。我曾经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 一样。

标签: node.jsasynchronouses6-promisemodule.exports

解决方案


我的做法是这样的。这是我的 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.

推荐阅读