并行运行相同的异步函数会导致变量混淆NodeJS



概要:

我在一个外部包装函数的await Promise.all()中运行下面的函数。该函数本质上做一些互联网抓取,然后将行添加到Postgres表中。我调用这个函数3次,使用分页偏移量来命中我需要的所有结果。

问题:

它添加了正确数量的行,但显然存在一些变量混淆,因为表中的输出有时具有重复数据(并且重复的数据因运行而异)。我认为这是因为在for循环的每次迭代中,它可能会从其他并发运行的函数之一引用内存中的数据。

代码:

const functionName = function (object, timestamp) {
new Promise(resolve => {
search.json(object, function (data) {
resolve(data);
})
}).then(data => async function () {
const client = await pool.connect();
try {
await client.query('BEGIN');
let results = data.results
if (results != null) {
for (result of results) {
let type = "item"
let title = result.title
var loop1 = result.loop1;
var loop2 = result.loop2;
let expiration = timestamp
var time = result.time;
await client.query(`INSERT INTO tableName (type, title, loop1, loop2, expiration, time) VALUES($1, $2, $3, $4, $5, $6) ON CONFLICT DO NOTHING`, [type, title, loop1, loop2, expiration, time]);
}
} else {
console.log("No results")
}
await client.query('COMMIT');
} catch (err) {
console.log(err)
await client.query('ROLLBACK');
}
}());
};

我怎样才能并行运行相同的函数,而不让其中一个变量对其他并发运行感到困惑?

for (result of results) {缺少变量声明。始终使用严格模式来避免隐式全局变量的恐怖!

那个箭头返回一个被传递给then的AIIFE是非常奇怪的。简化

async function functionName { /*
^^^^^^ */
const data = await new Promise(resolve => {
//             ^^^^^
search.json(object, resolve);
});
const client = await pool.connect();
try {
await client.query('BEGIN');
const {results} = data;
if (results != null) {
for (const result of results) {
//         ^^^^^
const type = "item"
const {title, loop1, loop2, time} = result;
const expiration = timestamp;
await client.query(`INSERT INTO tableName (type, title, loop1, loop2, expiration, time) VALUES($1, $2, $3, $4, $5, $6) ON CONFLICT DO NOTHING`, [type, title, loop1, loop2, expiration, time]);
}
} else {
console.log("No results")
}
await client.query('COMMIT');
} catch (err) {
console.log(err)
await client.query('ROLLBACK');
}
}

最新更新