简体   繁体   中英

js: str.replace() with Promise

I want to asynchronously replace a part of the string

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

})

console.log(str2)

I tried using async/await:

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

Inside the .replace callback, you can construct an array of Promises from the matched substrings, and then ignore the return value from .replace . From the array of Promises, call Promise.all on it to get an array of replacements. Then, call .replace again with the same pattern, and use the replacer function to replace each matched substring with the top item in the replacement array:

 // 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 });

Remove the then part it will return resolve or reject value

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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