how to resolve promise object in read clipboard function in javascript

To resolve a promise object in a read clipboard function in JavaScript, we can use the Navigator.clipboard.readText() method which returns a promise that resolves to the text that is currently on the clipboard. We can use the async/await keywords to ensure that the function returns a promise.

Here is the code block that resolves the promise returned by the readText() function:

index.tsx
async function readClipboard() {
  try {
    const clipboardText = await navigator.clipboard.readText();
    console.log(clipboardText);
    return clipboardText;
  } catch (err) {
    console.error('Failed to read clipboard contents: ', err);
  }
}
250 chars
10 lines

Here, we have defined an asynchronous function named readClipboard() that uses the await keyword to wait for the promise returned by navigator.clipboard.readText() to resolve. If the promise is resolved successfully, the function logs the clipboard text to the console and returns the text. If the promise is rejected due to an error, the function logs an error message to the console.

gistlibby LogSnag