破敗不堪:
我在外包裝函式的 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');
}
}());
};
我怎樣才能并行運行相同的函式,而不會使其中的變數對其他并發運行感到困惑?
uj5u.com熱心網友回復:
for (result of results) {缺少變數宣告。始終使用嚴格模式來避免隱式全域變數的恐怖!
此外,回傳 AIIFE 的箭頭then也很奇怪。簡化為
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');
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/462292.html
