javascript:在.replace中进行异步/等待

rit*_*078 8 javascript async-await es6-promise ecmascript-7

我正在通过以下方式使用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;
}
Run Code Online (Sandbox Code Playgroud)

但是返回的数据是一个Promise对象。只是对应该在带有回调的此类函数中实现它的方式感到困惑。

Ove*_*9ck 10

一个易于使用和理解的异步替换功能:

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());
}
Run Code Online (Sandbox Code Playgroud)

它执行两次替换功能,因此请注意是否要进行繁重的处理。不过,对于大多数用法来说,它非常方便。

像这样使用它:

replaceAsync(myString, /someregex/g, myAsyncFn)
    .then(replacedString => console.log(replacedString))
Run Code Online (Sandbox Code Playgroud)

或这个:

const replacedString = await replaceAsync(myString, /someregex/g, myAsyncFn);
Run Code Online (Sandbox Code Playgroud)

不要忘记您myAsyncFn必须兑现承诺。

asyncFunction的示例:

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())
        });
    });
}
Run Code Online (Sandbox Code Playgroud)

  • 但确实如此。它迭代并替换。 (3认同)

Chr*_*gan 10

Here\xe2\x80\x99s是 Overcl9ck\xe2\x80\x99s 答案的改进且更现代的版本:

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

String.prototype.matchAll这需要更新的浏览器基线,因为2019 年全面推出(Edge 除外,它在 2020 年初通过基于 Chromium 的 Edge 获得了它)。但它\xe2\x80\x99 至少同样简单,同时也更高效,只匹配第一次通过,而不是创建无用的字符串,并且不会以昂贵的方式改变替换数组。

\n

  • @lapo:我故意放弃了“shift”的用法,因为它对性能非常不利,无缘无故地将线性和只读的二次函数与写入转换。(我在答案中提到了这一点。) (2认同)

Ber*_*rgi 6

replace方法不处理异步回调,您不能将其与返回promise的替换器一起使用。

但是,我们可以编写我们自己的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("");
    });
}
Run Code Online (Sandbox Code Playgroud)


spe*_*der 5

因此,不存在承诺带来的替换过载。因此,只需重新声明您的代码即可:

async function(){
  let data = await someFunction();
  let output = string.replace(regex, data)
  return output;
}
Run Code Online (Sandbox Code Playgroud)

当然,如果您需要使用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("");
Run Code Online (Sandbox Code Playgroud)