0

I asked an earlier question last week concerning something kinda similar to this and it was immediately closed as I was referenced to a question about Asynchronous JavaScript. I tried to follow what seemed like the favorable opinion to use an asynchronous callback function, especially when using things like the fs module. However This code still does not continue to work. Are callbacks and other asyncs (like async functions/await) inherently different, and would they be more appropriate for this problem?

I am trying to return a buffer that is an html that I create appending fs reads from head, main (routeString variable) and tail html files.

What I don't get is why I can console.log the html buffer in the renderPage function, but it won't return that same buffer. Am I not able to return a buffer? I am really confused and have been stuck on this for a while.

const createPage = (routeString, callback) => {
    fs.readFile(`${__dirname}/head.html`, 'utf-8', (err, data) => {
        let header = data;

        fs.readFile(`${__dirname}/public${routeString}.html`, 'utf-8', (err, data) => {
            let main = data;

            fs.readFile(`${__dirname}/tail.html`, 'utf-8', (err, data) => {
                let tail = data;
                let page = header + main + tail;

                return callback(page);
            });
        });
    });
}

const renderPage = (result) => {
    console.log(result); // html/buffer prints!!
    return result;
}

let newPage = createPage('/training', renderPage); // string argument point to training.html when used in function

console.log(newPage); // undefined
  • @Barmar I would appreciate at least some form of response instead of just simply being directed to the same page everytime I post a question. There is a ton of information on that page and I read and tried to implement what I thought would be the correct solution. You also don't even attempt to acknowledge my other questions that I posed in this thread. I really don't think this question was that stupid and uninformed – Demetri Workman Jun 08 '20 at 20:34
  • The answers there clearly explain that the return value of the callback can't be returned here, since the callback runs asynchronously. If you want to write code that looks sequential, you need to convert it to `async` and `await`. – Barmar Jun 08 '20 at 20:38
  • @Barmar I didn't and still don't see it clearly. I'm still learning the language, not everyone is a seasoned veteran like you. But thanks for all the help I guess. I'll figure it out on my own – Demetri Workman Jun 08 '20 at 20:45
  • Put simply: asynchronous functions return immediately, they don't wait for the callback to finish. So it's not possible for the callback's return value to be returned to the original caller, since it already returned. – Barmar Jun 08 '20 at 20:46
  • Anything that needs to use `newPage` should be in the `renderPage` function. – Barmar Jun 08 '20 at 20:47

0 Answers0