繁体   English   中英

js: str.replace() 与 Promise

[英]js: str.replace() with Promise

我想异步替换字符串的一部分

var str = "abc"
var str2 = str.replace(/a/g,m=>{
  new Promise(r=>r("x"),j=>j("rejected"))
      .then(result=>result)

})

console.log(str2)

我尝试使用异步/等待:

var str = "abc"
var str2 = str.replace(/a/g, async(m)=>{
  return await new Promise(r=>r("x"),j=>j("rejected"))
      .then(result=>result)

})

console.log(str2) //[object Promise]bc

.replace回调中,您可以从匹配的子字符串构造一个.replace数组,然后忽略.replace的返回值 Promise.all数组中,对其调用Promise.all以获取替换数组。 然后,使用相同的模式再次调用.replace ,并使用 replacer 函数将每个匹配的子字符串替换为替换数组中的顶部项:

 // Replace the below function with the code required for your actual API call const getReplacement = str => Promise.resolve(`[${str}]`); const promises = []; var str = "abcabcb" str.replace(/[ab]/g, m => { promises.push(getReplacement(m)); }); Promise.all(promises) .then((results) => { const output = str.replace(/[ab]/g, () => results.shift()); console.log(output); }) .catch((err) => { // handle errors });

删除 then 部分,它将返回解决或拒绝值

var str = "abc"
var str2 = str.replace(/a/g, async(m)=>{
  return await new Promise((r,j)=>r("x"))
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM