如何在诺言链中使用循环/递归?

时间:2018-11-11 16:31:28

标签: javascript node.js ecmascript-6

例如,假设您要将分页数据从API存储到数据库。

let db;
let pageitems = 35
var offset = 0;

dbConnect //establish connection to database 
  .then( fetch(apiLink+?offset=2) 
  .then( res => res.json())
  .then( res => {
     var total = res.count
     return collection.insertMany(res.data, {ordered: false})
     // If offset is less than total, I want to increase offset and go back to the fetch-event.
  .catch( err => {
    if(err.code !== 11000){log(err)}
    else{log({completed: err.result.nInserted, duplicates: 
    err.result.result.writeErrors.length});}
  })
  .then(() => {
    connection.close();
  })

2 个答案:

答案 0 :(得分:1)

基本上,您将需要包装提取并将其插入将多次调用的函数中。请参阅以下示例以说明我的观点...

let db;
let pageitems = 35
var offset = 0;


var db = dbConnect() //establish connection to database 

function fetch_and_insert(offset) {
    db
    .then(fetch(apiLink + "?" + offset))
    .then(res => res.json())
    .then(res => {
        var total = res.count
        collection.insertMany(res.data, { ordered: false })
        .catch(err => {
            if (err.code !== 11000) { log(err) }
            else {
                log({
                    completed: err.result.nInserted, duplicates: err.result.result.writeErrors.length
                });
            }
        })
        if (offset < total) return fetch_and_insert(offset + pageitems)
        return null;
    })
}

fetch_and_insert(offset)
.then(() => {
    connection.close();
})

答案 1 :(得分:1)

您可以只使用常规循环:

static void Main(string[] args)
{
    long N = long.Parse(Console.ReadLine());
    long[] array = new long[N];
    long ODD = 1;
    long EVEN = 1;
    for (int i = 0; i < N; i++)
    {

        array[i] = int.Parse(Console.ReadLine());
        if ((i + 1) % 2 == 0)
        {
            EVEN *= array[i];
        }
        else
        {
            ODD *= array[i];
        }

    }

    if (EVEN == ODD)
    {
        Console.WriteLine("yes" +  " " +
            ODD);
    }
    else
    {
        Console.WriteLine("no" + " " + ODD + " " + EVEN);
    }
}

要加快速度,您可以并行执行多个请求:

 (async function() {
    const conn = await dbConnect;
    for(let offset = 0; true; offset++) { 
      const { data, count } = await (await fetch(`api?page=${offset}`)).json();
      // Exit if the page is empty
      if(count === 0) break;
      await collection.insertMany(data, { ordered: false });
    }
 })();