我有一个像这样的对象:
let myObject = {
'db1': [db1_file1Id,db1_file2Id,db_1file3Id],
'db2': [db2_file1Id, db2_file2Id]
...
}
我遍历这个对象并在每次迭代中:我连接到数据库,检索文件,执行一些操作并将文件保存回来。基本上是异步的东西。
for (let prop in myObject) {
if (myObject.hasOwnProperty(prop)) {
doStuff(prop, myObject[prop]);
}
}
现在 doStuff 函数确保我有一个本地范围,因此不会出现不一致。但由于每个循环内的异步操作,执行仍然不同步。我基本上需要完全处理一个数据库,然后才能继续处理下一个数据库。我该如何解决?
我想到的一种方法是使用递归循环。但根据我的理解,这需要我广泛改变我的数据结构,这在我看来是次优的。
let arr; //containing my data
process(x) {
if (x < arr.length){
//process(x+1) is called inside doStuff after asynchronous operations are complete
doStuff(arr[x]);
}
}
您可以使用您最后提出的解决方案Object.entries(obj)
。例如,
let arrProps = Object.entries(myObject);
process(index) {
if (index < arrProps.length){
// Call the callback once you complete execution of doStuff
doStuff(arrProps[index], () => process(index + 1));
}
}
内部 doStuff:
function doStuff(props, callback) {
// Process props
//finally in the promise of async call, on success call
.then(callback)
}
或者如果您想使用,您可以使用生成器函数for ... in
loop.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)