[英]Javascript Then() Promise is not working Asynchronously
I'm trying to figure out how to make this Firestore Collection asynchronously.我试图弄清楚如何异步制作这个 Firestore 集合。 I currently have it in a recursive function because a for loop wasn't working either.
我目前将它放在递归 function 中,因为 for 循环也不起作用。 I thought by using a recursive function it would give me more control for when I wanted to start the function over, but it's still not working.
我认为通过使用递归 function 可以让我更好地控制何时启动 function,但它仍然无法正常工作。 Please help.
请帮忙。 I know this would be something easy to solve for most people.
我知道这对大多数人来说很容易解决。
const fakeIt = async () => {
console.log("A");
var itemsCreated = 1;
items(0, itemsCreated);
async function items(num, itemsCreated){
if(num < itemsCreated){
console.log("B");
await db.collection('items').add({
active: true
}).then(async (item) => {
console.log("C");
items(num + 1, itemsCreated)
});
}else{
console.log("Done");
}
}
}
Array(2).fill(0).forEach(fakeIt);
The print out I'm getting is as follow:我得到的打印输出如下:
A
B
A
B
C
Done
C
Done
I need the result of:我需要以下结果:
A
B
C
A
B
C
Done
I figured it out by using a recursive function for the fakeIt loop.我通过对 fakeIt 循环使用递归 function 来解决这个问题。 I got rid of all of the async-await and everything works perfectly.
我摆脱了所有的异步等待,一切都很完美。 Thank to those that made the comments above.
感谢那些发表上述评论的人。
function fakeIt(number, count) {
if (number < count) {
console.log("A");
var itemsCreated = 1;
items(0, itemsCreated);
function items(num, itemsCreated){
if(num < itemsCreated){
console.log("B");
db.collection('items').add({
active: true
}).then(async (item) => {
console.log("C");
items(num + 1, itemsCreated)
});
}else{
fakeIt(number+1, count)
}
}else{
console.log("Done");
}
}
fakeIt(0, 2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.