在字符串替换中使用Promise

卢卡斯·蒂尔尼

我对诺言比较陌生,而且遇到了问题。

我有一个函数,希望能够对给定的文本进行一堆字符串替换,其中一些包含从api调用返回的值。

parseText(text) {
  text.replace(/\n|\r\n|\r/g, ' ')
  .replace(/&/g, '&')
  .replace(/&lt;/g, '<')
  .replace(/&gt;/g, '>')
  .replace(/<#(C\w+)\|?(\w+)?>/g, (match, id, read) => {
    return apiMethod(id).then(resp => resp.name)
  })
  .then(newText => {
    return newText.replace(/(-\w+)>/g, (match, id) => {
      apiMethod(id).then(resp => resp.name)
    }
  });
}

如何使替换与apiMethodpromise的返回值一起使用

一定的表现

一种选择是为每个请求创建一个Promises数组,调用Promise.all该数组,然后创建一个由id(正则表达式中的第一组)索引的对象然后,.replace再次调用,并用适当的索引键替换。因为您必须异步替换多次,所以将其放入自己的函数中以使代码变干:

const asyncReplace = async (str, regex) => {
  const promises = [];

  // does not actually replace anything, just builds the promises:
  str.replace(regex, (match, id, read) => {
    promises.push(apiMethod(id).then(resp => [id, resp.name]));
  });
  const results = await Promise.all(promises);
  const replacements = results.reduce((a, [id, name]) => {
    a[id] = name;
    return a;
  }, {});
  return str.replace(regex, (match, id, read) => replacements[id]);
}

parseText(text) {
  const str = text.replace(/\n|\r\n|\r/g, ' ')
  .replace(/&amp;/g, '&')
  .replace(/&lt;/g, '<')
  .replace(/&gt;/g, '>');
  return asyncReplace(str, /<#(C\w+)\|?(\w+)?>/g)
    .then((str2) => asyncReplace(str2, /<#(C\w+)\|?(\w+)?>/g))
}

现场摘要:

// encloses the match in underscores
const apiMethod = substr => Promise.resolve('_' + substr + '_');

const asyncReplace = async (str, regex) => {
  const promises = [];

  // does not actually replace anything, just builds the promises:
  str.replace(regex, (match, id, read) => {
    promises.push(apiMethod(id).then(resp => [id, resp]));
  });
  const results = await Promise.all(promises);
  const replacements = results.reduce((a, [id, name]) => {
    a[id] = name;
    return a;
  }, {});
  return str.replace(regex, (match, id, read) => replacements[id]);
}

function parseText(text) {
  // put underscores around every space...
  return asyncReplace(text, /( )/g)
  // ...twice:
    .then((str2) => asyncReplace(str2, /( )/g))
}
parseText('foo bar baz')
  .then(res => console.log(res));

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

在Java中使用替换字符串

在python中使用re替换字符串前后

如何在JavaScript中使用regexp替换字符串

在PL / SQL匿名块中使用替换字符串

在Java注释中使用Maven替换字符串

在 shell 脚本中使用替换字符串作为命令

vim:在替换命令中使用搜索中的字符串

在R中使用gsubfn()进行多字符串替换

在R中使用通配符拆分或替换字符串

在sed搜索/替换字符串中使用/

如何在jQuery中使用ltrim替换字符串?

在Sqlite中使用REGEX匹配和替换字符串?

在for循环中使用.subst替换字符串

别名替换字符串以在终端命令中使用它

Perl:在替换字符串变量中使用反向引用

在Matlab中使用strrep替换多个子字符串

在Java代码中使用Regex动态替换字符串

在c中使用字符串-扩展,替换,存储和打印字符串

在C#优化中使用替换和子字符串过滤字符串

在MySQL中使用Apostrophe替换字符串时运行查找和替换查询

在查找和替换字符串中使用sed和sed进行查找和替换

替换文件中的所有字符串,在替换中使用通配符

在Ubuntu中使用sed将字符串替换为特殊字符值

在React中使用html标签替换字符串之间的字符

在循环中使用数组替换字符串中的字符

如何在R中使用RegEx替换字符串中的字符

使用 shell 脚本在 DevOps 中使用替换字符串编辑文件

使用预制字符串和HTML中使用javascript的按钮进行文本替换

在python字符串中使用“ \”字符