简而言之:我有一个带有字符串参数并必须返回字符串的回调函数。我需要使用仅适用于流的库来转换此字符串。我该怎么办?
更长:我正在使用Node.js replacestream,它具有匹配RegEx的功能,就像String.replace一样,它允许指定a callback function for replacing。我需要做的是获取匹配的字符串,通过另一个库运行它,然后返回转换后的字符串进行替换。
问题在于该库仅适用于流。通常,我可以使整个事情异步进行,但我看不到有任何方法可以通过String.replace回调来实现。
src(['*.js'])
.pipe(replace(/`(.*?)`/gs, function(match, p1, offset, string) {
var ostream = stringtostream(p1);
ostream.pipe(glslminify());
//???code that waits for ostream to finish and converts it to string???
return string_from_ostream;
}))
.pipe(dest(jsdest));
一定有更好的方法可以做到这一点,所以我在寻找任何建议。
答案 0 :(得分:1)
您已经澄清了该库使用流,并且重要的是,它异步地执行其工作。这意味着您不能直接在replace
回调中使用它来确定回调的返回值,因为当然必须同步提供该返回值。
相反,您可以做的是使函数异步,将字符串分为需要处理的部分和不需要处理的部分,触发需要处理的部分的异步处理,然后在需要处理的部分组装完成的字符串。完成。
下面是一个使用异步异步过程通过promise报告完成情况的示例(您可以在流中包装promise,或者改编代码以使用流完成):
// Your function for processing the string
function yourFunction(str) {
return Promise.all(
str.split(/`(.*?)`/s).map((fragment, index) =>
// The capture groups are the odd-numbered indexes
index % 2 === 1
? process(fragment)
: fragment
)
)
.then(segments => segments.join(""));
}
// The promise wrapper around the library
function process(str) {
return new Promise((resolve, reject) => {
// Emulate via timer; I'm not emulating failure here, but
// you'd handle failure by calling `reject`
setTimeout(() => {
// Success
resolve(str.toUpperCase());
}, Math.random() * 400);
});
}
// Testing with and without leading and trailing text
yourFunction("`one two three` testing `two three four`")
.then(result => {
console.log(result);
return yourFunction("leading text `one two three` testing `two three four`")
})
.then(result => {
console.log(result);
return yourFunction("leading text `one two three` testing `two three four` trailing text")
})
.then(result => {
console.log(result);
})
.catch(error => {
// Handle/report error
});