Promise.all时出错(关闭连接/挂断)"/>
做Promise.all时出错(关闭连接/挂断)
我正在使用[email protected]包,我有很多数据要导出到Google表格,
现在我使用此代码
const insertDataToSheet = async (data, sheet, msg) => {
let query = []
try {
data.map(async item => {
query.push(promisify(sheet.addRow)(item))
})
const result = await Promise.all(query)
if (result) return result
throw new Error(`${msg} Unkown Error`)
} catch (e) {
throw new Error(`${msg} Failed: ${e.message}`)
}
}
此代码适用于100个或更少的数据,但是如果我使用150+个数据,则连接不支持它。
错误列表
- Client network socket disconnected before secure TLS connection was established
- Socket hang up
- Error: HTTP error 429 (Too Many Requests)
Promise.all
有什么限制吗?
或
回答如下:有没有更好的解决方案将批量/批量数据导出到Google电子表格?
Promise.all
将在其中一个诺言引发时引发。如果即使一个承诺失败也要继续执行操作,则不希望像上面的代码中那样将其重新抛出。
您可以将其重新添加到挂起的队列中,然后重试。
此外,我可能会考虑将其批处理。将它们分成大块并上传。
示例:
创建一个工作池(工作数量= cpu核心数量(默认))
使用工作程序池运行上传逻辑
模拟错误/用Math.random
重试
process.js
文件
const path = require('path')
const _ = require('lodash')
const Pool = require('piscina')
const BB = require('bluebird')
const workerPool = new Pool({
filename: path.resolve(__dirname, 'worker.js'),
})
const generateData = (numItems = 5) => {
return Array.from({ length: numItems }, (v, idx) => 'item ' + idx)
}
const CHUNK_SIZE = 10
const data = generateData(100)
const chunks = _.chunk(data, CHUNK_SIZE)
BB.map(
chunks,
(chunk) => {
workerPool.runTask(chunk)
},
{ concurrency: 1 /* 1 chunk at a time */ }
)
worker.js
文件
const retry = require('p-retry')
// your upload logic here
function process(data) {
if (Math.random() > 0.5) {
console.log('processing ', data)
} else {
console.log('fail => retry ', data)
throw new Error('process failed' + data)
}
}
module.exports = (data) => {
return retry(() => process(data), { retries: 10 })
}
使用node process.js
运行
更多推荐
做Promise.all时出错(关闭连接/挂断)
发布评论