简体   繁体   English

我如何使用递归 function 在 javascript 中推送数组

[英]How could I use the Recursion function to push array in javascript

I am trying to use the recursion function to push the data in the tempList, however no matter how to fix the code still is an empty array.我正在尝试使用递归 function 来推送 tempList 中的数据,但是无论如何修复代码仍然是一个空数组。

let tempList=[]
var getWineList =  function(database_name,locaDataBase){
    return new Promise(async (sucess,fail)=>{


        wineList(0,database_name)
        console.log(tempWineList)
        sucess("a")
    })
}

function wineList(currentPosition,database_name){

    let wines= db.collection(database_name)
    .skip(currentPosition)
    wines.get()
        .then((res)=>{


            // tempList.forEach(function(wine,index){
            //  tempWineList.push(wine)
            // })

            if(res.data.length<20){
                console.log(res.data)
                return res.data

            }
            tempWineList.push(res.data)
            return tempList.push(wineList(currentPosition+20,database_name))
        })


}

Method wines.get() is asynchronous.方法wines.get()是异步的。 It means, that it don't returns value immediately, but it only returns a promise - promise that it will return value in future.这意味着它不会立即返回值,但它只返回 promise - promise 它将在未来返回值。 In your code you push to an array inside then , so it won't be executed immediately, but when promise will be resolved, but inside getWineList function you don't wait for it to happen and execute console.log before that data is pushed.在您的代码中,您推送到内部的数组then ,因此它不会立即执行,但是当 promise 将被解析时,但在getWineList function 内部您无需等待它发生并在推送该数据之前执行console.log .

So the solution is to return promise from wineList function and wait before doing console log.所以解决方案是从wineList function 返回 promise 并在执行控制台日志之前等待。 You can do it in 2 ways: by then() or async / await您可以通过 2 种方式执行此操作:通过then()async / await

Example of using async / await :使用async / await的示例:

let tempList=[]
var getWineList =  async function(database_name,locaDataBase){
    await wineList(0,database_name)
    console.log(tempWineList)
    return "a";
}

function wineList(currentPosition,database_name){

    let wines = db.collection(database_name)
    .skip(currentPosition);

    let res = await wines.get();

    if(res.data.length<20){
        console.log(res.data)
        return res.data
    }
    tempWineList.push(res.data)
    return tempList.push(wineList(currentPosition+20,database_name))
})

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM