2

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
Sh eldeeb
  • 1,589
  • 3
  • 18
  • 41
  • Will each replacement replace the same thing? Eg if `a` is replaced, it'll always be replaced with the same replacement character/substring? – CertainPerformance Jan 29 '20 at 07:32
  • No, the real process is to replace base64 encoded data with it's src link after uploading to the cloud. – Sh eldeeb Jan 29 '20 at 07:33
  • So if the same base64 data is found twice, you'll construct *two separate links* for it, are you sure? That sounds pretty odd – CertainPerformance Jan 29 '20 at 07:34
  • 3
    `new Promise(r=>r("x"),j=>j("rejected"))` I really think you need a refresher course in how Promises are created – Jaromanda X Jan 29 '20 at 07:34
  • 1
    @JaromandaX I'm pretty sure that part is just there for a minimal example of "I have a Promise here, how do I consume it and replace properly?" – CertainPerformance Jan 29 '20 at 07:35
  • Do you need the process to be completed after some event or you just want to shift the normal execution to event queue?? – Shubham Dixit Jan 29 '20 at 07:35
  • 2
    *I want to asynchronously replace a part of the string* - why? - besides the fact that replace callback doesn't support that, so **nothing** you can do to make it work, why would you WANT that? – Jaromanda X Jan 29 '20 at 07:35
  • @CertainPerformance - I really think the OP is clueless about the Promise constructor – Jaromanda X Jan 29 '20 at 07:36
  • I want to perform an uploading process to the cloud to obtain the link, then replace base64; part of the string with it's link. – Sh eldeeb Jan 29 '20 at 07:37
  • The `Promise` doesn't use the match (hence the example doesn't make much sense). So just get the value and replace it in `.then()`. – Andreas Jan 29 '20 at 07:43
  • @Sheldeeb it's better you update your question with a real/complete problem rather asking about you think the solution can be. – AZ_ Jan 29 '20 at 07:46
  • 1
    Does this answer your question? [javascript : Async/await in .replace](https://stackoverflow.com/questions/33631041/javascript-async-await-in-replace) – Ivan Kahl Jan 29 '20 at 07:47
  • I find it strange that you'd need to do this async, string edditing is so immensely fast that I doubt it's necessary. anyway. I googled somewhat and I figured this could probably help you: https://medium.com/javascript-in-plain-english/async-await-javascript-5038668ec6eb It's a guide to promises since Async-Await are extentions of promises. – FllnAngl Jan 29 '20 at 08:19

2 Answers2

1

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
  });
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • just because OP wants the `fish to fly`? :D – AZ_ Jan 29 '20 at 07:44
  • this will run getReplacement(m) immediately – Sh eldeeb Feb 05 '20 at 16:52
  • 1
    @Sheldeeb No, `getReplacement` is asynchronous - see how it returns a Promise? You can replace it with anything else asynchronous (like the actual logic for your network request) and the overall logic will still work fine. – CertainPerformance Feb 06 '20 at 00:01
  • (1) You're not using the same regular expression in the first `.replace` as in the second. The first RE is `/-/`, which matches `-` in `a-b`, but the second RE is `/'-'/`, but there are no `'`s, so no matches occur. (2) Since the replacement is asynchronous, you must put everything inside the `Promise.all`'s `.then` call – CertainPerformance Feb 07 '20 at 01:25
-3

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"))
})
sathish kumar
  • 1,477
  • 1
  • 11
  • 18