0

I have written a library function pRead(Path), which returns a JavaScript Promise to read a file on the local computer under an Apache server, using Ajax. I won't include the code for this, as it uses standard technology that is well-known to anyone who can give a good answer to this question.

I want to write a second library function, pReadObj(Path), which will return a Promise to read a JSON file and provide its object value to asynchronous code. It should work like this:

pReadObj("test.json").then(then2).catch(pErr);
function then2(obj)
    {
    alert(JSON.stringify(obj)); // Shows the JSON obj
    } // then2

Here is the code I wrote:

var globalPreviousResolve;

function pReadObj(Path) // Promise to read JSON from file
    {
    return new Promise(function(resolve,reject)
        {
        globalPreviousResolve=resolve;
        pRead(Path).then(pReadObj2).catch(pErr);
        });
    } // pReadObj

function pReadObj2(JSONStr)
    {
    globalPreviousResolve(JSON.parse(JSONStr));
    } // pReadObj2

function pTestDB() // Called from button
    {
    pReadObj("test.json").then(then2).catch(pErr);
    } // pTestDB

This works, but has a problem: using a global variable to hold the resolve callback is not only ugly, but it will clearly malfunction if two calls to pReadObj happen within a short period of time and the disk read takes a longer time than that.

The resolve function needs to be stored inside the Promise in some way, I'm thinking.

David Spector
  • 1,520
  • 15
  • 21

1 Answers1

2

There's no need to explicitly create a Promise; just return the one created by .then:

function pReadObj(Path) {
  return pRead(Path).then(JSON.parse);
}
AuxTaco
  • 4,883
  • 1
  • 12
  • 27
  • Wow. That works. So simple and elegant, the way arguments are handled implicitly. Promises are remarkable. Thanks, AuxTaco. – David Spector Aug 26 '19 at 20:57