我目前正在开发Electron.js应用程序,但遇到了异步问题。我在三个if语句中依次执行三个函数(downdloadFile()),但它们异步运行;我已经尝试过使用async / await,但是没有用。 这是我的代码:
ipcMain.on('play',(event,payload) => {
launcherConfig.savedRam = payload.savedRam;
launcherConfig.savedMaxPermSize = payload.savedMaxPermSize;
if(payload.selectedPacket) {
//FIRST IF
if (!fs.existsSync(launcherDir + "\\natives")) {
downloadFile("http://soulnetwork.it/launcher/natives.zip", launcherDir + "\\natives.zip", true, 'natives');
}
//SECOND IF
if (!fs.existsSync(launcherDir + "\\bin")) {
downloadFile("http://soulnetwork.it/launcher/bin.zip", launcherDir + "\\bin.zip", true, 'bin');
}
//THIRD IF
if (launcherConfig.installed_modpacks.includes(payload.selectedPacket)) {
launchMinecraft(payload.selectedPacket);
saveConfig();
} else {
downloadFile(`http://soulnetwork.it/launcher/modpacks/${payload.selectedPacket}.zip`, launcherDir + "\\modpacks\\" + payload.selectedPacket + '.zip', true, payload.selectedPacket, launchMinecraft);
launcherConfig.installed_modpacks.push(payload.selectedPacket);
saveConfig();
}
}
}
function downloadFile(file_url , targetPath, showProcess, packetName, callback){
// Save variable to know progress
var received_bytes = 0;
var total_bytes = 0;
var req = request({
method: 'GET',
uri: file_url
});
var progressWindow = null;
if(showProcess){
progressWindow = new BrowserWindow({width: 300, height: 60, title: `Downloading ${packetName}`,icon: '../public/images/sn.png'})
progressWindow.setProgressBar(0.0);
progressWindow.loadURL('file://' + __dirname + '/views/download.ejs');
progressWindow.setMenu(null);
}
var out = fs.createWriteStream(targetPath);
req.pipe(out);
req.on('response', function ( data ) {
// Change the total bytes value to get progress later.
total_bytes = parseInt(data.headers['content-length' ]);
});
req.on('data', function(chunk) {
// Update the received bytes
received_bytes += chunk.length;
if(showProcess)
showProgress(progressWindow,received_bytes, total_bytes);
});
req.on('end', function() {
if(showProcess)
progressWindow.close();
if(targetPath.includes('.zip')){
var zip = new archiver(targetPath);
zip.extractAllTo(targetPath.substr(0,targetPath.length-4-packetName.length));
fs.unlinkSync(targetPath);
}
if(callback)
callback(packetName);
console.log("RETURN");
return;
});
}
使用回调系统会产生很多麻烦,而且这也是多余的,我希望能找到其他解决方案。 谢谢您的时间!
答案 0 :(得分:2)
当前console.log("RETURN")
所在的位置可以解决downloadFile
返回的Promise。然后,您可以简单地等待if
分支中的调用(并将async
回调传递给ipcMain
当然)。
采用更简单形式的结构如下所示
function doJob () {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log('RETURN')
resolve()
}, 2000)
})
}
// ipcMain.on('play', async (event, payload) => { ... })
(async () => {
if (true) {
await doJob()
}
if (true) {
await doJob()
}
})()
答案 1 :(得分:0)
我可以看到您在所有三个时间里都对launcherDir产生了影响!即使在操作失败的情况下,它也会始终执行第一个进程,即如果正在检查则最后一个进程 launcherDir +“ \ natives” +“ \ bin”还是这是期望的行为,否则我认为您所有的if都会失败