Friday 21 April 2017

Returning Promises within Asynchronous Functions

In short my questions are:

  1. If using bluebird should inherently be "promisifying" things?
  2. Under these cases should I just callan explicit Promise.(resolve|reject) within the sub Asynchronous function, and attach a return to it, like the format for the 2nd function?
  3. I may be understanding the control flow of the promises incorrectly, when everything is good within the fs.readFile things will go as they should, is the async code not simulating a return when it meets that reject?
  4. What happens to the running Async Function after the Promise has been rejected? Does it just return the result to that awaiting Promise, and then the Async code is left hanging around, doing whatever it wants until compltion?

    • Is it basically just treating the whole thing like one big generator, without a yield telling it to stop executing at this point?
  5. I have one last question, but searching it up would likely answer it. Is my promise chain methodology proper? I've used them before, and every once in a while I run into the unhandled rejection issue. I am setting up a catch block, and doing so in favor of running with format .then((res)=>{...}, (rej)=>{...}) as its an antiPattern as stated by the PromisesA+ conventions.

.

I've been running into this recently with regards to my using Promises, and i somewhat understand the logic behind the behavior stated, but some parts are not fully clicking.

The issue is that I have some code that's calling up an asynchronous function, for the sake of relating this to most users of Node using fs.readFile. When executing the code below, I keep running into situations under which the Promise is rejecting, or getting into it's reject clause, but the rest of the function is being executed.

I get the reason why the second iteration works, due to the returns enforcing the native control flow, but I also think of the Promise wrapper around the function call as instating it's own flow control, and once it's resolve/reject function is triggered, the function is terminated. This does not seem to be the case, as the function will reject, and fall through into it's resolve statement. Breaking anything else that pops up with it. The same behavior is seen under other sub-functions , i.e. running request that fails, and other async functions. I am unsure if it will also affect Synchronous code as well.

NOTE

The Below Snippet will not run outside of NodeJs, I don't yet know how to deal with it in JSFiddle, and the required fs module is, I believe, node specific.

/*
 Seemingly bypassing my Promise's reject statements
 This does not only happen with fs, but with other none natively promise based sub
 libraries.
 Is it because I am not inherrently promisifying things, should I just return a Promise.resolve within the sub Asynchronous function, and attach a return to it, like the format for the 2nd function?
 
I may be understanding the control flow of the promises incorrectly, when everything is good within the fs.readFile things will go as they should, since the last thing being done is basically resolving, and the control flow is implicitly acting like that native flow.
 */
const Promise = require('bluebird'),
  fs = require('fs'),
  fName = './tmpFs.txt';

const retPromExample = () => {
  return new Promise((resolve, reject) => {
    fs.readFile(fName, (err, fd) => {
      if (err) {
        // The if condition is applied and satisfied
        console.log("\nI got in here, and I know I've failed %s\n", err);
        reject(err)
      }
      // It still gets here, even though err is clearly not null, if the file does not exist
      console.log("I'm outside the if(err) with ", err);
      // Do something with the file, try and JSON.parse it, and fd is undefined.
      resolve("What I wanted to do was done. Resolving\n")
    })
  })
};

const retPromExample_deux = () => {
  // On the rejection getting an unhandled rejection error as well. Am I following the syntax for this correctly?
  return new Promise((res, rej) => {
    return fs.readFile(fName, (err, fd) => {
      if (err) {
        // The if condition is applied and satisfied
        return Promise.reject("Part Deux; I got in here, and I know I've failed %s \n", err)
      }
      // Under this case an explicit return is given, it should not reach here. If the file does not exist. Err should be null.
      console.log("I'm outside the if(err) with ", err);
      // Base control Flow states that this should not fail in any manner.
      return Promise.resolve("What I wanted to do was done. Resolving")
    })
  })
};

// Toggle which is run with node FSTest.js 1 or Nothing.
if (process.argv.find(val => val === '1'))
  retPromExample()
  .then(val => console.log(val))
  .catch(err => console.log(err));
else
  retPromExample_deux()
  .then(val => console.log(val))
  .catch(err => console.log(err));


via L.P.

No comments:

Post a Comment