javascript - 在字符串替换中使用 promise

标签 javascript

我对 promises 比较陌生,但遇到了一些问题。

我有一个函数,我希望能够对给定的文本进行一堆字符串替换,其中一些包含从 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)
    }
  });
}

如何使用 apiMethod promise 的返回值进行替换?

最佳答案

一个选项是为每个请求创建一个 Promise 数组,在该数组上调用 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));

关于javascript - 在字符串替换中使用 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52417975/

相关文章:

javascript - 如何使用鼠标位置确定文本颜色

javascript - Angular 2 JSONP 请求中未发送授权 header

javascript - 使用 JS/jQuery 获取位置固定的元素

javascript - 为什么我的 div 在较小的屏幕上可以拖动,但是当我在较大的屏幕上检查它时,我不再能够拖动它?

javascript - jquery mobile listview - 在 <li> 元素上触发的 touchstart 事件

javascript - 使用 Google map 触发标记和标记簇上的点击事件

javascript - 我的 if else 语句未按预期工作 - 所有语句的innerHTML 保持不变

javascript - 选择特定父元素并将其与同级元素一起包裹,直到下一个特定父元素

javascript - 使用 javascript 选择下拉值(Bookly WP 插件)

javascript - 强制使用特定的 ES 版本