我创建了一个http服务器。在创建服务器之前,我检查数据库连接。如果db已关闭..将再次调用check方法,直到它连接为止。在此之后我启动服务器。启动服务器后,我需要检查几个配置设置。服务器启动正常。我编写了一个代码,用于依次调用3个配置设置验证码。但是,两个方法同时执行,最后一个方法根本不被调用。
//检查与其他应用的连接
function checkconfig1() {
return request.post({
headers: {
'content-type': 'application/json'
},
url: url,
}, function(error, response, body) {
if (body == 'success') {
//config 1 is verified
console.log("config 1 is verified")
}
if (error) {
console.log("config 1 is not correct")
return Promise.delay(2500).then(checkconfig1);
}
});
}
function checkconfig2() {
return request.get({
headers: {
'content-type': 'application/json'
},
url: url,
}, function(error, response, body) {
if (error) {
console.log("config 2 is not correct")
return Promise.delay(2500).then(checkconfig2);
} else {
console.log("config 2 is verified")
}
});
}
function checkconfig3() {
var cmd = 'somecommand';
return exec(cmd, function(error, stdout, stderr) {
if (error) {
console.log("config 2 is not correct")
return Promise.delay(2500).then(checkFonts);
} else {
console.log("config 2 is verified")
}
});
}
module.exports = function() {
return checkconfg1().then(checkconfig2).then(checkconfig3());
//return checkFonts();
}
我做得对吗?任何人都可以解释如何做到这一点?感谢
答案 0 :(得分:1)
我已经修改了一下你的代码。 你能试试这个:
function checkconfig1() {
return new Promise(function (resolve, reject) {
request.post({
headers: {
'content-type': 'application/json'
},
url: url,
}, function (error, response, body) {
if (body == 'success') {
//config 1 is verified
console.log("config 1 is verified")
return resolve();
}
if (error) {
console.log("config 1 is not correct")
return resolve(Promise.delay(2500).then(checkconfig1));
}
});
});
}
function checkconfig2() {
return new Promise(function (resolve, reject) {
request.get({
headers: {
'content-type': 'application/json'
},
url: url,
}, function (error, response, body) {
if (error) {
console.log("config 2 is not correct")
return resolve(Promise.delay(2500).then(checkconfig2));
} else {
console.log("config 2 is verified")
return resolve(response);
}
});
});
}
function checkconfig3() {
var cmd = 'somecommand';
return new Promise(function (resolve, reject) {
exec(cmd, function (error, stdout, stderr) {
if (error) {
console.log("config 2 is not correct")
return resolve(Promise.delay(2500).then(checkFonts));
} else {
console.log("config 2 is verified")
return resolve();
}
});
});
}
module.exports = function () {
return checkconfig1().then(checkconfig2).then(checkconfig3);
//return checkFonts();
};