等待异步功能完成,然后在Express中进行app.listen

时间:2019-11-06 10:35:56

标签: javascript node.js express asynchronous cors

我试图从数据库中获取CORS的白名单,但是显然我要先开始监听端口并设置CORS,然后才能从数据库中获取值。

那是我的代码:

require('dotenv').config()
import jwt from 'jsonwebtoken'
import bcrypt from 'bcryptjs'

//Express and helmet setup
import helmet from 'helmet'
import express from 'express'
const app = express()

app.use(helmet())

//CORS
import { query } from 'graphqurl'

const gqlAPI = process.env.GRAPHQL
const hasuraAdmin = process.env.HASURA_ADMIN
const whiteList = []

const getWhiteList = async function() {
    await query({
        query: `
            query getWhiteList {
                whitelist {
                    origin
                }
            }
        `,
        endpoint: gqlAPI,
        headers: {
            'content-type': 'application/json',
            'x-hasura-admin-secret': hasuraAdmin
        }
    }).then(res => {
        return res.data.whitelist
    })
    .then(res => {
        res.map(value => (
            whiteList.push(value.origin)
        ))
    })
    .catch(err => { throw new Error(err)})
}
getWhiteList()

import cors from 'cors'
const corsOptions = {
    origin: function (origin, callback) {
        if (whitelist.indexOf(origin) !== -1 || !origin) {
          callback(null, true)
        } else {
          callback(new Error('Not allowed by CORS'))
        }
    }
}

app.use(cors(corsOptions))

//listening
const PORT = process.env.PORT || 3001
app.listen(PORT, () => {
    console.log('whitelist:', whiteList)
    console.log(`Listening on PORT: ${PORT}`)
})

输出为“白名单:[]”

有没有一种方法可以让我等待异步功能的结束后再开始监听?

对不起,我的英语不好,希望您能明白我的意思。

谢谢

2 个答案:

答案 0 :(得分:1)

实现所需目标的最简单方法是将app.listen方法调用实际包装在.then方法中。

精确地:

getWhiteList().then(() => {
  // [...] More code that might reference the whitelist
  app.listen(PORT, () => {
    console.log('whitelist:', whiteList)
    console.log(`Listening on PORT: ${PORT}`)
  });
});

答案 1 :(得分:0)

将其包装为自调用异步功能,我认为它将起作用

(async () => {

const whiteList = await getWhiteList();

const corsOptions = {
    origin: function (origin, callback) {
        if (whitelist.indexOf(origin) !== -1 || !origin) {
          callback(null, true)
        } else {
          callback(new Error('Not allowed by CORS'))
        }
    }
}

app.use(cors(corsOptions))

//listening
const PORT = process.env.PORT || 3001
app.listen(PORT, () => {
    console.log('whitelist:', whiteList)
    console.log(`Listening on PORT: ${PORT}`)
})

})()