Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can't return value from RTF parser #34

Open
8483 opened this issue Jul 13, 2022 · 1 comment
Open

Can't return value from RTF parser #34

8483 opened this issue Jul 13, 2022 · 1 comment

Comments

@8483
Copy link

8483 commented Jul 13, 2022

Maybe I need a break from coding, but I really don't get why I can't retrieve the value from the function...

Can anyone please tell me what I'm doing wrong?

const parseRTF = require("rtf-parser");

let string = `{\\rtf1\\ansi\\deff0\\nouicompat{\\ etc...}`;

function convertRTFtoPlainText(string) {
    parseRTF.string(string, (err, doc) => {
        let result = "";

        doc.content.forEach((item) => {
            if (item.content) {
                item.content.forEach((span) => {
                    result += span.value;
                });
            }
        });

        console.log(result);           // <-------- Shows the converted string

        return result.trim();
    });
}

let value = convertRTFtoPlainText(string);   

console.log(value);                    // <-------- undefined
@Romick2005
Copy link
Contributor

Romick2005 commented Jul 13, 2022

You should use Promise here

const parseRTF = require("rtf-parser");

function convertRTFtoPlainText(str) {
  return new Promise(
    function(resolve, reject) {
      parseRTF.string(
        str,
        function (error, doc) {
          if (error) {
            return reject(error);
          }

          let result = "";

          doc.content.forEach((item) => {
            if (item.content) {
              item.content.forEach((span) => {
                result += span.value;
              });
            }
          });

          resolve(result.trim());
        }
      );
    }
  );
}

const string = `{\\rtf1\\ansi\\deff0\\nouicompat{\\ etc...}`;

convertRTFtoPlainText(string).then(
  function (value) {
    console.log('convertRTFtoPlainText = ' + value);
  }
).catch(
  function (error) {
    console.error('Error in convertRTFtoPlainText', error)
  }
);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants