Javascript - 异步函数完成后下一行如何等待执行
Javascript - How next line wait to be executed after asyncronus function is done?
我正在使用Phonegap插件中的FileTransfer.download功能在我的应用程序移动设备中下载文件。
此函数是 assyncronus,因此执行下一行时不依赖于此函数的结论。
我的应用应用在登录过程中从服务器捕获用户照片,因此在此操作结束后无法将用户移动到主屏幕。但是对于我的实际代码,它不会发生,因为我不知道该怎么做。
您可以在下面检查我的代码:
var usuarios = json.usuarios;
var fileTransfer = new FileTransfer();
for(var key in usuarios) {
if(usuarios.hasOwnProperty(key)){
if(usuarios[key].tipo == "titular"){
var titular = {
"id" : usuarios[key].id,
"email" : $("#login-email").val(),
"foto" : "images/perfil.jpg"
};
localStorage.setItem('appnowa-titular', JSON.stringify(titular));
if(usuarios[key].foto == "1"){
window.fileDownloadName = "appnowa-perfil-" + usuarios[key].id + ".jpg";
console.log('downloadFile');
window.requestFileSystem(
LocalFileSystem.PERSISTENT,
0,
function(fileSystem){
console.log('onRequestFileSystemSuccess');
fileSystem.root.getFile(
'dummy.html',
{create: true, exclusive: false},
function(fileEntry){
console.log('onGetFileSuccess!');
var path = fileEntry.toURL().replace('dummy.html', '');
var fileTransfer = new FileTransfer();
fileEntry.remove();
fileTransfer.download(
'https://www.myserver.com/imagens/clientes/' + window.fileDownloadName,
path + window.fileDownloadName,
function(file) {
console.log('download complete: ' + file.toURL());me;
titular.foto = file.toURL();
},
function(error) {
console.log('download error source ' + error.source);
console.log('download error target ' + error.target);
console.log('upload error code: ' + error.code);
titular.foto = "images/perfil.jpg";
}
);
},
fail
);
},
fail
);
console.log("1 " + titular.foto);
}
}
}
}
localStorage.setItem('appnowa-dependentes', JSON.stringify(dependentes));
appNowa.pushPage('mainPage.html'); //go to next page
我认为您可以通过两种方式实现它,
链式回调或在所有回调中进行状态测试;
我将编写我认为可能是工作解决方案的伪代码(未经测试,不保证)
afterCharge=function(){
doYourStuffHere;
}
//method 1 in your callback
var complete=0
len = usuarios.lenght;
for(var key in usuarios){
//do yourstuff
fileTransfer.download(
file,
path,
function(file){
//do your stuff
complete++;
if(len===complete){
afterCharge();
}
},
function(error){
//do your stuff
complete++;
if(len===complete){
afterCharge();
}
}
);
}
相关文章:
- 单击按钮以等待单击按钮
- React组件等待所需道具进行渲染
- 拆分文本以每隔n个字符添加一行新行,并注意空格
- 动态插入的表:JQuery未检测到最后一行
- 在终端中运行 JavaScript 时(使用 rhino),如何使用 print() 函数在一行中打印
- 如何在Angular UI网格中选择下一行
- 通过单击动态加载的表中同一行的另一个字段来更新一行的字段
- 正在等待呈现图表,直到加载数据为止
- 在等待ajax请求时显示微调器并禁用页面
- Javascript在for循环中等待处理请求
- JavaScript循环并等待函数
- 在等待异步任务时永久循环
- 在通过child.print()打印之前,我如何等待图像加载到我的新窗口中
- Javascript - 异步函数完成后下一行如何等待执行
- 如何在执行下一行之前等待执行完成
- JQuery在执行下一行代码之前等待几秒钟
- 如何在执行下一行代码之前等待主干事件触发器完成
- 如何等待按钮生成,然后执行下一行代码
- Javascript在执行下一行之前不会等待STRIPE.COM函数完成
- Do函数在执行到下一行之前不等待执行完成