Node JS中每个操作的顺序异步操作

问题描述

正在进行数据库迁移。这需要查询一个数据库获取记录数组并执行一组异步操作,以将数据插入新数据库中。为了保持数据的一致性,我想一次插入一个记录,所以我希望每个操作都按顺序运行。我发现做到这一点的唯一方法是使用递归。

有没有一种更清洁的方式来做同样的事情?我知道有一个名为async https://caolan.github.io/async/v3/的库,我从未尝试过。

我编写的递归方法如下:

const insertItem = async (data) => {
    let item = data[0];

    if (!item) {
        //I am done return
        return;
    }

    try {
        //Do multiple await calls to insert record into new database
    } catch (e) {
        //Recover from error (DB rollbacks,etc)
    } finally {
        //Remove inserted or Failed item from collection.
        data.shift();
        await insertItem(data);
    }
};

//Query original database
getInfo().then((data) => insertItem(data));

解决方法

您可以使用同步循环for...of,它将等待HTTP响应。

const dataArr = ['data1','data2','data3'];

async function processItems(arr){
  for(const el of arr) {
    const response = await insertData(el);    
    // add some code here to process the response.
  }
};

processItems(dataArr);

,

在调用单个函数以递归方式处理所有事情之前,所发布的代码通过使用data.shift对自变量数组进行突变来遍历从第一个数据库检索的数据集合(数组)。

要清理此问题,请通过将数据处理功能分成两个来删除shift和递归调用:

  • 一个功能来逐步浏览从第一个数据库中检索到的数据,
  • 第二个功能,可根据需要在第二个数据库中插入记录。

这消除了对.finally子句的需要,并使代码的结构看起来更像

async function insertData(data) {
    for( let index = 0 ; index < data.length; ++index) {
        await insertItem( data[index]);
    }
}

async function insertItem( data) {
    try {
        //Do multiple await calls to insert record into new database
    } catch (e) {
        //Recover from error (DB rollbacks,etc)
        // throwing an error here aborts the caller,insertData()
    }
}

getInfo().then( insertData).catch( /*... handle fatal error ...*/);

根据首选样式,可以将insertItem声明为insertData中的嵌套函数,以使其看起来整洁,并且可以将insertData编写为{{1 }}在then之后致电。

当然可以通过其他方法顺序执行异步操作,但是在getInfo()函数中使用await也许是最简单的编码方法。