Javascript Async


const ftp = require("basic-ftp")
const client = new ftp.Client()

let AWS = require('aws-sdk');
let sns = new AWS.SNS();

module.exports.publish = async (event) => {
    const listening = await client.access({
            host: 'ip-address',
            user: 'user',
            password: 'password'
    }).then(async()=>{
         return client.list()
    });
    
    const p_array = listening.map((directory)=>{
        const path = '/'+(directory.name) ;
        return wrap(path)
    })
    
    return Promise.all(p_array).then(async()=>{
        await client.close();
    })

};

function wrap(directory){
    const params = {
      Message: directory,
      TopicArn: 'arn:aws:sns:us-east-2:760202155994:topic-name'
    };
    
    const p = sns.publish(params).promise();
    
    return p.catch((err) => {
        console.error(err, err.stack);
    });
    
}


//ftp
const ftp = require("basic-ftp")
const client = new ftp.Client()

//aws services
let AWS = require('aws-sdk');
let sns = new AWS.SNS();

Jacascript async function definition

Search for: Jacascript async function definition

understand javascript promises

Search for: understand javascript promises

what is an arrow function in javascript?

Search for: what is an arrow function in javascript?

whose passes resolve and reject in a promise?

Search for: whose passes resolve and reject in a promise?

That is explained here


PromiseObj -> Run Executor code (inline typically)
  internal-resolve-method
  internal-reject-method

//Pass these two methods as inputs to the
//executor

//Loopy but that now makes sense

//the executor is a function definition
//not function invocation!!!
//So it only names its params!!

//So the receiver of the executor function
//has the responsibility to pass
//the needed callbacks!!

Official doc on promis

Appends fulfillment and rejection handlers to the promise, and returns a new promise resolving to the return value of the called handler, or to its original settled value if the promise was not handled (i.e. if the relevant handler onFulfilled or onRejected is not a function).


Promise p = foo();

//p is a multivalued return
//with status pending
//it is an active value


function doThisOnGood(value){}
function doThisIfFails(){}

p.then(doThisOnGood, doThisIfFails);

The then function of Promises in Javascript

Search for: The then function of Promises in Javascript

Chaining and then explained in this SOF question

Once a Promise is fulfilled or rejected, the respective handler function (onFulfilled or onRejected) will be called asynchronously (scheduled in the current thread loop).

The then is explained better here (hopefully)

P1 is typically returned by a function. Likely that function when completes calls P1's functions to inform done or not done.

Before the P1 is fulfilled, one way or the other, the then handlers are setup on P1 right away by calling the then function. P1 will keep these functions in its safe keep until it is fulfilled. As part of the "then" setup P1 assigns a new P2 which is set to be fulfilled when the P1's then handlers are finished. Finsihed means right away or asynchronously depending on how those handlers are programmed.

P2 is smart enough to know whether the then handlers that resulted in P2 returns another promise or not.

Anyway what results is a hierarchy of promises that can be setup to be chained through their then handlers.

Each then is invoked after the completion of the previous then, be it sync or async.

Arrow functions in Javascript

Search for: Arrow functions in Javascript


var materials = [
  'Hydrogen',
  'Helium',
  'Lithium',
  'Beryllium'
];

elements.map(function(element) {
  return element.length;
}); // this statement returns the array: [8, 6, 7, 9]

// The regular function above can be 
// written as the arrow function below
elements.map((element) => {
  return element.length;
}); // [8, 6, 7, 9]

elements.map(element => element.length); // [8, 6, 7, 9]

//essentially implying the return statement and 
//function body

An arrow function does not have its own this. The this value of the enclosing lexical scope is used; arrow functions follow the normal variable lookup rules. So while searching for this which is not present in current scope they end up finding this from its enclosing scope.

Thus, in the following code, the this within the function that is passed to setInterval has the same value as this in the lexically enclosing function:

Arrow functions do not have their own arguments object. Thus, in this example, arguments is simply a reference to the arguments of the enclosing scope:

Read up on other nuances of arrow methods here


var Foo = () => {};

// TypeError: Foo is not a constructor
var foo = new Foo(); 

// Because they don't have a "this" to take in

var Foo = () => {};
console.log(Foo.prototype); // undefined

Javascript await

Search for: Javascript await


//lets call f1 an async func
async f1() { return "a"};

var x = f1();

//x will not be "a"
//x will be an implicit Promise (object)
//So you can do

x.then(result => console.log(result))

//lets call f1 an async func
async doThis() { return "a"};

//Do this later

doThis();

//When the event loop get around to it
//So doThis() is scheduled to be done later

Will async/await block a thread node.js on SOF

Quote: So, while the whole interpreter doesn't block (other Javascript events can still be serviced), the execution of the specific async function that contains the await statement was suspended until the promise that was being awaited resolved. What's important to understand is step 5 above. When the first await is hit, the function immediately returns an unresolved promise and code after this function is executed (before the promise being awaited is resolved). It's for this reason that the whole interpreter is not blocked. Execution continues. Only the insides of one function are suspended until a promise is resolved.

Interesting, so Javascript has a way to suspend a function execution while executing the rest of the code!!

because that the function is expected to return only a Promise and the client knows to expect its full return using the "then" construct!

So, the code in the function block below, await() will not be executed as if it is sync call, but the not the code outside of that function.

I suppose the JS engine must have had some capabilities to do so understanding what comes, what statements come, after the await() syntactically


// foo is an async function that returns a promise
await foo();            
console.log("hello");

//is analogous to this:

foo().then(() => {
    console.log("hello");
});

//So the intepretter may be wrapping the code inside
//an invisible "then" 
//its possible so 
//without changing the execution environment
//That makes more sense

So the invisible "await" is like an "invisible then", the rest follows


Promise
Promise Chaining
Then
Arrow functions
Await
Async

Return now, but Do the following later

How can I resolve a promise outside of its executor function in Javascript

Search for: How can I resolve a promise outside of its executor function in Javascript

Here is an example from Github on a basic promise creation

Here is a more involved example from Github

I will elaborate on these two samples later

1. When you tag a function as an async, it means, when called, that function will complete at some point in future

2. So the async function returns a promise object to track when that function will complete

3. The value returned by the async function will be returned "through" the Promise object

4. The async function makes a provision for "await". waiting for an internal or additional promise to complete

5. Async function "logically" returns at the point of an await

6. The await waits for that promise but will return the thread to the called

7. The promise to be waited upon can be a compound promise

8. The await mechanism allows the code to be read as if it is synchronous and sequential

9. await does not return a promise. it returns the result of the promise on which it is waiting

10. The returned result of that promise is used by subsequent lines of that function

11. It is possible to write an async function as a plain function with very similar capabilities

12. The async and the await makes that look simpler

Although the mechanisms of Promise, Async, and await are fairly clear from the beginning I was not able to figure out "how closely related" they were. Meaning are they independent concepts? could they be used with out the other?

It turns out async and await are keywords that allow you to use "promises" in simpler ways.

And Promises themselves are simpler ways to use the event loop and hence to use deferred execution.


//Consider these utility functions

f1
f2
//one that takes longer now
//but just a regular function
//uses a promise and deferred execution
pf3
f4
f5

//Now consider working with those functions 
//to do something useful

async function af()
{
  //These will be executed right away
  f1
  f2

  //This will return right away
  //with a fake promise
  let x = await pf3

  //the following will execute
  //in the "then" portion of "pf3"
  f4(x)
  f5

  //This will go back to the promise of af()
  return "hello";
}

let y = af();
y.then (){}

//y will contain "hello" eventually
//y is a promise
//y.then is called after the "hello" is returned

hint: it requires chaining of the inside "then" of pf3 promise