我正在使用bluebird Promise映射来处理文件行数组,其中一些行需要进行一些转换。调用Web服务即可完成转换。
我编写了一个函数,该函数返回一个promise,该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"));
});
});
}
Run Code Online (Sandbox Code Playgroud)
但是,processed与的顺序不同data,我需要保持相同的顺序(因为这是文件处理,需要以与输入文件相同的顺序输出处理后的文件)。
这是Tokenize函数(调用Web服务):
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);
}
});
});
}
Run Code Online (Sandbox Code Playgroud)
如何保持数组顺序并返回相同数组但已转换?考虑到该Web服务能够处理超过1000 TPS。
Promise.map 解析值是一个数组,其中每个元素按顺序是每个回调的返回/解析值。
因此,无需推送到数组,只需返回推送的值即可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")
}
Run Code Online (Sandbox Code Playgroud)
您可以删除new Promise()包装器,制作函数async,使代码更清晰。
| 归档时间: |
|
| 查看次数: |
563 次 |
| 最近记录: |