[英]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.