[removed] Async/await in .replace

前端 未结 4 1318
情话喂你
情话喂你 2021-02-05 06:00

I am using the async/await function the following way

async function(){
  let output = await string.replace(regex, async (match)=>{
    let data = await someF         


        
4条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-05 06:08

    The native replace method does not deal with asynchronous callbacks, you cannot use it with a replacer that returns a promise.

    We can however write our own replace function that deals with promises:

    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("");
        });
    }
    

提交回复
热议问题