javascript 浏览器:异步/等待输入. replace

ddhy6vgd  于 2023-01-24  发布在  Java
关注(0)|答案(7)|浏览(264)

我将按照以下方式使用async/await函数

async function(){
  let output = await string.replace(regex, async (match)=>{
    let data = await someFunction(match)
    console.log(data); //gives correct data
    return data
  })
  return output;
}

但是返回的数据是一个promise对象,只是对在这样的带回调的函数中应该如何实现感到困惑。

l0oc07j2

l0oc07j21#

一个易于使用和理解的异步替换函数:

async function replaceAsync(str, regex, asyncFn) {
    const promises = [];
    str.replace(regex, (match, ...args) => {
        const promise = asyncFn(match, ...args);
        promises.push(promise);
    });
    const data = await Promise.all(promises);
    return str.replace(regex, () => data.shift());
}

它会执行两次替换功能,所以如果你要处理一些很重的东西,要小心。不过对于大多数用途来说,它还是很方便的。
像这样使用它:

replaceAsync(myString, /someregex/g, myAsyncFn)
    .then(replacedString => console.log(replacedString))

或者这个:

const replacedString = await replaceAsync(myString, /someregex/g, myAsyncFn);

不要忘记,您的myAsyncFn必须返回一个承诺。
异步函数的示例:

async function myAsyncFn(match) {
    // match is an url for example.
    const fetchedJson = await fetch(match).then(r => r.json());
    return fetchedJson['date'];
}

function myAsyncFn(match) {
    // match is a file
    return new Promise((resolve, reject) => {
        fs.readFile(match, (err, data) => {
            if (err) return reject(err);
            resolve(data.toString())
        });
    });
}
imzjd6km

imzjd6km2#

native replace method不处理异步回调,您不能将其与返回承诺的替换器一起使用。
然而,我们可以编写自己的replace函数来处理承诺:

async function(){
  return string.replace(regex, async (match)=>{
    let data = await someFunction(match)
    console.log(data); //gives correct data
    return data;
  })
}

function replaceAsync(str, re, callback) {
    // http://es5.github.io/#x15.5.4.11
    str = String(str);
    var parts = [],
        i = 0;
    if (Object.prototype.toString.call(re) == "[object RegExp]") {
        if (re.global)
            re.lastIndex = i;
        var m;
        while (m = re.exec(str)) {
            var args = m.concat([m.index, m.input]);
            parts.push(str.slice(i, m.index), callback.apply(null, args));
            i = re.lastIndex;
            if (!re.global)
                break; // for non-global regexes only take the first match
            if (m[0].length == 0)
                re.lastIndex++;
        }
    } else {
        re = String(re);
        i = str.indexOf(re);
        parts.push(str.slice(0, i), callback.apply(null, [re, i, str]));
        i += re.length;
    }
    parts.push(str.slice(i));
    return Promise.all(parts).then(function(strings) {
        return strings.join("");
    });
}
xqnpmsa8

xqnpmsa83#

因此,不存在需要承诺的replace重载,所以只需重新编写代码即可:

async function(){
  let data = await someFunction();
  let output = string.replace(regex, data)
  return output;
}

当然,如果需要使用match值传递给异步函数,事情会变得有点复杂:

var sourceString = "sheepfoohelloworldgoocat";
var rx = /.o+/g;

var matches = [];
var mtch;
rx.lastIndex = 0; //play it safe... this regex might have state if it's reused
while((mtch = rx.exec(sourceString)) != null)
{
    //gather all of the matches up-front
    matches.push(mtch);
}
//now apply async function someFunction to each match
var promises = matches.map(m => someFunction(m));
//so we have an array of promises to wait for...
//you might prefer a loop with await in it so that
//you don't hit up your async resource with all
//these values in one big thrash...
var values = await Promise.all(promises);
//split the source string by the regex,
//so we have an array of the parts that weren't matched
var parts = sourceString.split(rx);
//now let's weave all the parts back together...
var outputArray = [];
outputArray.push(parts[0]);
values.forEach((v, i) => {
    outputArray.push(v);
    outputArray.push(parts[i + 1]);
});
//then join them back to a string... voila!
var result = outputArray.join("");
avkwfej4

avkwfej44#

以下是Overcl9ck’s answer的改进版和更现代的版本:

async function replaceAsync(string, regexp, replacerFunction) {
    const replacements = await Promise.all(
        Array.from(string.matchAll(regexp),
            match => replacerFunction(...match)));
    let i = 0;
    return string.replace(regexp, () => replacements[i++]);
}

由于String.prototype.matchAll,这需要一个更新的浏览器基线,landed across the board in 2019(除了Edge,它在2020年初获得了基于Chromium的Edge).但它至少同样简单,同时也更高效,只在第一次通过时 * 匹配 *,而不是创建一个无用的字符串,并且不会以昂贵的方式改变替换数组.

mznpcxlj

mznpcxlj5#

下面是使用递归函数的另一种方法:

async function replaceAsync(str, regex, asyncFn) {
    const matches = str.match(regex);
    if (matches) {
        const replacement = await asyncFn(...matches);
        str = str.replace(matches[0], replacement);
        str = await replaceAsync(str, regex, asyncFn);
    }
    return str;
}
1l5u6lss

1l5u6lss6#

还有另一个解决方案,这次使用TypeScript,与Maxime's solution类似,它避免了许多其他解决方案中“语义上不寻常”的初始replace()-调用,而是使用match()

async function replaceAsync(str: string, regex: RegExp, asyncFn: (match: string) => Promise<string>): Promise<string> {
  const promises = (str.match(regex) ?? []).map((match: string) => asyncFn(match));
  const data = await Promise.all(promises);
  return str.replace(regex, () => data.shift()!);
}
j9per5c4

j9per5c47#

这是Overcl9ck在TS中实现的解决方案:

const replaceAsync = async (str: string, regex: RegExp, asyncFn: (match: any, ...args: any) => Promise<any>) => {
    const promises: Promise<any>[] = []
    str.replace(regex, (match, ...args) => {
        promises.push(asyncFn(match, args))
        return match
    })
    const data = await Promise.all(promises)
    return str.replace(regex, () => data.shift())
}

相关问题