Javascript if-else中承诺和同步代码的组合
以下内容包含Javascript if-else中承诺和同步代码的组合,javascript,if-statement,asynchronous,Javascript,If Statement,Asynchronous,以下内容包含ifelse中的承诺、同步语句。是否有一种方法可以按顺序执行它,即片段1、2、3、4,并使用thenchain将其保存在一个片段中,而不是将每个片段作为一个函数并为每个if-else调用它们?例如,无论类别是否为MAIN,片段2、3、4都应该在片段1之后执行 // Start Fragment 1 if (category == "AUXILIARY") fncAuxiliary() //synchronous function if (categ
if
else
中的承诺、同步语句。是否有一种方法可以按顺序执行它,即片段1、2、3、4,并使用then
chain将其保存在一个片段中,而不是将每个片段作为一个函数并为每个if-else调用它们?例如,无论类别是否为MAIN,片段2、3、4都应该在片段1之后执行
// Start Fragment 1
if (category == "AUXILIARY") fncAuxiliary() //synchronous function
if (category == "MAIN") fncMain() // returns promise
// End Fragment 1
// Start Fragment 2
if (category != "AUXILIARY")
if (type == "REGRADE") {
fncSelectProduct().then( () => { // returns promise
//other synchronous code
fncProduct1(); //synchronous function
});
}
else{
fncSelectProduct().then( () => { // returns promise
//other synchronous code
fncProduct2(); //synchronous function
});
}
// End Fragment 2
// Start Fragment 3
if (type == "REGRADE") {
//synchronous code
}
else if (category !="AUXILIARY") {
//synchronous code
}
else if (category =="AUXILIARY") {
//synchronous code
}
// End Fragment 3
// Start Fragment 4
if (category !="AUXILIARY")
if(type == "MECHANICAL"){
fncSelectEquipment().then( () => { // returns promise
//other synchronous code
return fncEq1() // returns promise
}).then( () => {
//synchronous code
});
}
else if(type == "OPERATIONAL"){
fncSelectOpsEquipment().then( () => { // returns promise
//other synchronous code
return fncEq2() // returns promise
}).then( () => {
//synchronous code
});
}
else if(type == "PROCESS"){
//synchronous code
}
else if(type == "ROUTINE"){
//synchronous code
}
// End Fragment 4
您可以使用async Wait轻松地处理此问题。将内容链接到中,最终会使您的代码看起来很混乱。有关代码的异步等待版本,请参阅下面的代码段
const fragment = async (category) => {
if (category == "AUXILIARY") console.log("Hello"); //synchronous code
if (category == "MAIN") await fetch("/").then(console.log, console.error);
if (category)
await fetch("/").then(() => console.log("This runs after previous fetch"));
};
const main = async () => {
await fragment("MAIN");
console.log("Code after fragment");
};
main();
您可以在此处阅读有关async/await的更多信息-最简单的解决方案是
async
/await
。但不需要,您需要将每个片段代码放在一个函数中——这并没有错。不过,您不需要为其命名,请参见例如。