gpt4 book ai didi

Node.js 异步模块需要

转载 作者:太空宇宙 更新时间:2023-11-04 01:47:24 24 4
gpt4 key购买 nike

我有一个关于基于 Express 的 Node.js 应用程序的问题,该应用程序依赖于第一个 require()。这是我的第一个 Node.js 应用程序。第一个 require() 访问 AWS ec2 参数存储来收集数据库的凭据。在以异步方式解决此需求之前,我无法连接到数据库。

我发现执行此操作的最佳方法是导出回调并将其余的 require() 语句包装在第一个 require() 的回调中。 这是一种不好的做法吗?

//app.js

var appConfig = require('./config/appconfig');

appConfig.fetchAppConfig(function(err, result) {
if(err) {
console.log(err);
console.error("Server failed to startup. Config parameters not available.");
}
else {
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
...
app.use(bodyParser.json());
etc
...

//appConfig.js

module.exports = function fetchAppConfig(callback) {
getCredentials(function(err, result) {
if(err) {
console.log(err);
callback(err);
} else {
awsLogin.paramStoreService(result).then(
data => {
appConfig = decodeAppConfig(data.Parameter.Value);
callback(null, appConfig);
}
).catch(
error => {
console.error(error);
callback(err);
}
)
}
})
}

我错过了一个更简单的选择吗?

使用此逻辑将配置提取到部署代码中的某个位置是否会更好?

最佳答案

我将定义几个函数,一个用于请求凭据,另一个用于在检索凭据后连接到数据库。您可以使用 async模块的series函数可以让您轻松控制应用程序的流程。

来自文档:

Run the functions in the tasks collection in series, each one running once the previous function has completed. If any functions in the series pass an error to its callback, no more functions are run, and callback is immediately called with the value of the error. Otherwise, callback receives an array of results when tasks have completed.

这是一个例子:

var async = require('async');

function getCredentials(callback) {
callback(null, {
user: 'hello',
pass: 'world',
});
};

function connectToDatabase(callback, creds) {
console.log('Connecting to database => ' + JSON.stringify(creds));

callback(null, 'Done');
};

async.series([
getCredentials,
connectToDatabase,
],
function(err, results) {
console.error(err);
console.log(results);
});

关于Node.js 异步模块需要,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50974313/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com