很抱歉提出一个似乎已经以无数种方式详细解答的问题,我了解JS的异步特性,但是我所阅读的关于promise和callbacks的无数论着并没有帮助我编写有效的代码。 / p>
我有2个与API交互的函数,我只想能够以一种可以在另一个之后运行的方式来调用它们。
这是我的两个功能:
let pveNextid = "";
function getNextID() {
var clientServerOptions = {
method: 'GET',
uri: apiRoot + "/cluster/nextid",
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Cookie': pveCookie,
}
}
request(clientServerOptions, function(error, response) {
pveNextid = JSON.parse(response.body).data;
console.log("Next VMID: " + pveNextid);
})
}
// Create a new container with specs defined in conf.js
function newContainer() {
var clientServerOptions = {
method: 'POST',
uri: apiRoot + "/nodes/" + conf.pveNode + "/lxc",
form: {
net0: "bridge=vmbr0,name=eth0,ip6=auto",
ostemplate: conf.pveTemplate,
vmid: pveNextid,
unprivileged: 1,
storage: "local-lvm",
memory: 320,
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Cookie': pveCookie,
'CSRFPreventionToken': pveCSRF,
}
}
request(clientServerOptions, function(error, response) {
console.log(response.body);
})
};
必须有一种简单的方法(如几行可读的方法)?
答案 0 :(得分:0)
最简单的方法是提供对函数的回调,以便在请求完成后为您提供运行某些代码的挂钩,您也可以通过这种方式摆脱全局变量:
// Take a callback here
function getNextID(callback) {
var clientServerOptions = {
method: 'GET',
uri: apiRoot + "/cluster/nextid",
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Cookie': pveCookie,
}
}
request(clientServerOptions, function(error, response) {
var pveNextid = JSON.parse(response.body).data;
console.log("Next VMID: " + pveNextid);
// call the callback and give it the information you want to provide to the function
callback(pveNextid);
})
}
// Create a new container with specs defined in conf.js
// take the pveNextid here
function newContainer(pveNextid) {
var clientServerOptions = {
method: 'POST',
uri: apiRoot + "/nodes/" + conf.pveNode + "/lxc",
form: {
net0: "bridge=vmbr0,name=eth0,ip6=auto",
ostemplate: conf.pveTemplate,
vmid: pveNextid,
unprivileged: 1,
storage: "local-lvm",
memory: 320,
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Cookie': pveCookie,
'CSRFPreventionToken': pveCSRF,
}
}
request(clientServerOptions, function(error, response) {
console.log(response.body);
})
};
// call getNextId and provide the callback here that you want to run after the first request
getNextId(newContainer);
我建议对回调使用promise,async / await和其他更可维护的解决方案,但是在这种情况下,这是一个简单的解决方案。