0

I create a function which saves in a variable text the content of my clipboard.

I want to return the function output to another variable called my_text, however I am not able to do so. I have to do that since I want to apply some NLP algorithm to my_text

I get my_text is undefined

function paste() {
  navigator.clipboard.readText()
  .then(text => {

    console.log(text);
    return text
  })
  .catch(err => {
    console.error("Failed to read clipboard contents: ", err);
  });

}

var my_text = paste()`

I think it is because my function paste() is async, but I am still not sure how to assign what it returns to a variable.

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
Prova12
  • 643
  • 1
  • 7
  • 25

2 Answers2

1

You're not returning anything from the function - only the inner functions.

return navigator.clipboard.readText().then(...).catch(...);

Alternatively, use an async function.

async function paste() {
  try {
    const text = await navigator.clipboard.readText();
    console.log(text);
    return text;
  } catch(er) {
    console.log(err);
  }
}
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
  • Thanks, I tried that too but I get: `[[PromiseStatus]]: "resolved", [[PromiseValue]]: "undefinied"`. I would like the "text" to be returned. – Prova12 Jun 18 '19 at 00:10
  • If I use the alternative, I get `await is only valid in async function` – Prova12 Jun 18 '19 at 00:14
  • 1
    Fixed, try now @Prova12. – Jack Bashford Jun 18 '19 at 00:14
  • Thanks, now `[[PromiseValue]]:` contains the text I want. I have to find out how to assign it to my variable `my_text` because now it return the promise while I just want to the content of `[[PromiseValue]]:` – Prova12 Jun 18 '19 at 00:19
0

You are not returning anything from your paste function. Try this.

  function paste() {
    navigator.clipboard
      .readText()
      .then(text => {
        //call another function
        //or simply do the paste operation here
        processTextFurther(text);
      })
      .catch(err => {
        console.error("Failed to read clipboard contents: ", err);
      });
  }

  function processTextFurther(copiedText) {
    console.log(copiedText);
  }
Belal Khan
  • 2,099
  • 2
  • 22
  • 32
  • Thanks, now `[[PromiseValue]]:` contains the text I want. I have to find out how to assign it to my variable my_text because now it return the promise while I just want to the content of `[[PromiseValue]]:` – Prova12 Jun 18 '19 at 00:33
  • You can assign it in to `processTextFurther` function and then do whatever you want with it. – Belal Khan Jun 18 '19 at 00:49