我正在使用 bluebird Promise 映射来处理一组文件行,其中一些行需要进行一些转换。调用 Web 服务完成转换。
我写了一个函数,它返回一个用转换后的数组解析的 promise 。
function tokenizeChunk(data){
return new Promise(async (resolve, reject) => {
let processed = [];
await Promise.map(data, async (line) => {
try{
const lineCode = line.substring(0,4);
if (lineCode != "0500") processed.push(line);
else{
// find string, tokenize, replace
const stringFound = line.substring(55,71);
var re = new RegExp(stringFound,"g");
processed.push(line.replace(re, await Tokenize(stringFound)));
}
}catch(err){
console.error(err);
process.exit();
}
}, {concurrency: 50}).then(() => {
resolve(processed.join("\r\n"));
});
});
}
但是,processed
和data
的顺序不一样,我需要保持相同的顺序(因为这是一个文件处理,需要输出处理后的数据)与输入文件顺序相同的文件)。
这是 Tokenize 函数(调用网络服务):
function Tokenize(value){
return new Promise(function(resolve, reject){
var requestPath = `http://localhost:8080/transform/${value}`;
request.get(requestPath, function(err, response, body){
if (!err && response.statusCode == 200){
resolve(body);
}else{
reject(err);
}
});
});
}
如何保持数组顺序并返回相同但已转换的数组?考虑到网络服务能够处理超过 1000 TPS。
最佳答案
Promise.map
resolved value 是一个数组,其中每个元素按顺序是每个回调的返回/解析值。
因此,不是推送到数组,而是返回推送的值,Promise.map
将为您处理订单。
async function tokenizeChunk(data) {
const result = await Promise.map(data, async(line) => {
const lineCode = line.substring(0, 4);
if (lineCode != "0500")
return line;
// find string, tokenize, replace
const stringFound = line.substring(55, 71);
var re = new RegExp(stringFound, "g");
return line.replace(re, await Tokenize(stringFound));
}, { concurrency: 50 });
return result.join("\r\n")
}
你可以去掉new Promise()
包装器,让函数async
,让代码更清晰。
关于node.js - promise map 保持秩序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50788928/