简体   繁体   English

在Promise中使用for循环

[英]using for loop inside promises

I am having a scenario where Step 1: i have run a loop and push the data into an array step 2: once my first loop is complete I will start second loop to push data into the same array 我遇到的情况是:步骤1:我已经运行了一个循环并将数据推入数组中步骤2:一旦我的第一个循环完成,我将开始第二个循环以将数据推入同一数组中

I have tried async function, this is my example use case 我已经尝试过异步功能,这是我的示例用例

  var arr =[]; //declared globally
    async function myloop(){

    for(i=0;i<10;i++){
    arr.push(i);
    }

    }

   // Here is what I wanna do now
    myloop().then(function(){
    for(i=10;i<20;i++){
    arr.push(i)
    }
    })

I have to wait until my function pushes all the data in the loop, after loop completion I need to come back here for second run 我必须等到我的函数将所有数据推送到循环中之后,循环完成后,我需要回到这里进行第二次运行

The context is a bit unclear, but I assume that you are receiving two arrays from two collections, which returns the array in a Promise . 上下文还不清楚,但是我假设您正在从两个集合中接收两个数组,这将在Promise返回该数组。

Let's suppose you have these two functions. 假设您具有这两个功能。

function dataBaseCallX() {
    // returns a Promise<Array>
}

function dataBaseCallY() {
    // returns a Promise<Array>
}

And you want to combine both the results right? 您想将两个结果结合起来吗? Then here you can use the async-await feature. 然后,您可以在此处使用async-await功能。 I think this is what you want. 我想这就是你想要的。

const resultA = await dataBaseCallX();  // An Array
const resultB = await dataBaseCallY();  // An Array

let combinedResults = resultA.concat(resultB);

If in case of errors, you can simply wrap this into a try catch block. 如果出现错误,可以将其包装到try catch块中。

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

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