[removed] Async/await in .replace

前端 未结 4 1308
情话喂你
情话喂你 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:07

    So, there's no overload of replace that takes a promise. So simply restate your code:

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

    of course, if you need to use the match value to pass to the asynchronous function, things get a bit more complicated:

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

提交回复
热议问题