我正在使用bluebird Promise map来处理一组文件行,其中的一些行需要进行一些转换。转换是通过调用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函数(调用webservice):
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);
}
});
});
}
如何保持数组顺序并返回经过转换的相同数组?考虑到webservice能够处理超过1000个TPS。
发布于 2018-06-11 08:23:56
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")
}
您可以删除new Promise()
包装器,使函数成为async
,从而使代码更清晰。
发布于 2020-01-17 22:34:42
Promise.map
不保证执行顺序-如果需要,可以使用Promise.each
或Promise.reduce
,并且可以进行顺序处理。
https://stackoverflow.com/questions/50788928
复制相似问题