How do I return value from inner function without creating chain of return? - node.js

function xyz() {
function abc() {
function haha() {
return 5;
}
return haha();
}
return abc();
}
console.log(xyz());
I get '5' in console. Thats ok. Its a simple code of larger problem where there is lots of nested functions. I dont want to return one after the other. Is there any way, I can return from any function and return it to original function caller.

function xyz() {
function abc() {
return 5;
}
return abc()
}
console.log(xyz());

ok maybe you need call backs. I don't get the context of what you are trying to do but I'll just try.
function logTheAnswer (a) {
console.log(a)
}
function add(a, b, cb) {
cb(a + b)
}
add(1,2,logTheAnswer)
now you can nest the call backs indefinitely though try to keep it a minimum as you will experience call back hell.

Sorry to say but your question is a bit confusing without a proper output representation. But you can use callback functions with which you can easily manage your nested calls and returns.
function myFunc3(a, b, callback3){
callback3(a+b);
}
function myFunc2(a, b, c, callback2){
myFunc3(a+c, b, function(result2){
callback2(result2);
})
}
function myFunc1(){
myFunc2(a,b,c, function(result1){
console.log(result1);
})
}

Add a return the from abc function call
function xyz() {
function abc() {
return 5;
}
return abc();
}
console.log(xyz());
Or return an IIFE (Immediately Invoked Function Expression)
function xyz() {
return (function abc() {
return 5;
})();
}
console.log(xyz())

Related

Value returning from an async function is not the actual value

I'm calling an async function that has the file path as a parameter and reads and displays the content in the file.
this is the place where I'm invoking the function.
this is the function.
After reading the contents in the file, the data is printed in the console.
But when I try to use the same value to display in the emulator I'm getting error.
Why actual string value is not returned from the function??
error.
readContent is a future method, you need to wait to complete the fetching.
For future method, try using FutureBuilder.
late Future future = readContent();
#override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder(
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text("${snapshot.data}");
}
return CircularProgressIndicator();
},
),
);
}
Find more about using FutureBuilder.
An async function in dart can only return a Future.
Your readContent function signature doesn't declare a return value:
readContent(String path) async {
var result = await File(path).readAsString();
print(result);
return result
}
If you explicitly declare the return value as String you'll get a compilation error. Async methods can only return a future:
Future<String> readContent(String path) async {
var result = await File(path).readAsString();
print(result);
return result
}
The await keyword allows you to access the value returned by a Future, it is not the same as calling the function synchronously.
The only reason you need the await keyword in your code is because you're printing the value to console when the Future completes. You could do this instead, which is the same function without printing to console and without async await.
readContent(String path) {
return File(path).readAsString();
}
To address the issue described in your question, you might call readAsString synchronously:
readContent(String path) {
return File(path).readAsStringSync();
}
Or use await on the calling side
var val = await readContent(path);
Or
var txt = "";
readContent(path).then((value) {
txt = value;
setState(() {});
});
Or use the FutureBuilder widget

TS decorator to wrap function definition in try catch

Is it possible to use TS decorator to wrap a function definition into a try-catch block. I don't want to use try-catch in every function so I was thinking maybe decorators can help.
For example
function examleFn(errorWrapper: any) {
try{
// some code
} catch (err) {
errorWrapper(err)
}
}
Something like this can be done in a decorator so that it can be used for other functions too.
No, you cannot decorate functions.
TypeScript's implementation of decorators can only apply to classes, class methods, class accessors, class properties, or class method parameters. The relevant proposal for JavaScript decorators (at Stage 3 of the TC39 Process as of today, 2022-07-21) also does not allow for decorating functions.
Function decorators are mentioned as possible extensions to the decorator proposal, but are not currently part of any proposal for either TypeScript or JavaScript.
You can, of course, call a decorator-like function on another function, but this is just a higher-order function and not a decorator per se, and it won't affect the original function declaration:
const makeErrorWrapper = <T,>(errorHandler: (err: any) => T) =>
<A extends any[], R>(fn: (...a: A) => R) =>
(...a: A): R | T => {
try {
return fn(...a);
} catch (err) {
return errorHandler(err);
}
};
The makeErrorWrapper function takes an error handler and returns a new function that wraps other functions with that error handler:
const errToUndefined = makeErrorWrapper(err => undefined);
So now errToUndefined is a function wrapper. Let's say we have the following function which throws errors:
function foo(x: string) {
if (x.length > 3) throw new Error("THAT STRING IS TOO LONG");
return x.length;
}
// function foo(x: string): number
If you call it directly, you can get runtime errors:
console.log(foo("abc")); // 3
console.log(foo("abcde")); // 💥 THAT STRING IS TOO LONG
Instead you can wrap it:
const wrappedFoo = errToUndefined(foo);
// const wrappedFoo: (x: string) => number | undefined
Now wrappedFoo is a new function that behaves like foo and takes the same parameter list as foo, but returns number | undefined instead of just number:
console.log(wrappedFoo("abc")) // 3
console.log(wrappedFoo("abcde")) // undefined
Playground link to code
maybe this can help you, it took me a long time to do it, but here it is
function Execpetion (methodName: string) {
return (target: any, nameMethod: string, descriptor: PropertyDescriptor) => {
const originalMethod = descriptor.value
descriptor.value = async function (...args: any[]) {
try {
const executionMethod = await originalMethod.apply(this, args)
return executionMethod
} catch (error) {
return errorWrapper(error as Error)
}
}
}
}
in your class
class TestController {
#Execpetion('TestController')
public async handler (teste: any) {
return {
statusCode: 200,
data: 'nothing'
}
}
}
with the parent function, you can modify and add to receive the errorPersonalized and instantiated type parameter... and on the return put it

Nodejs Set a global function and call a nested function

My Main function
import AppLauncher from './Applauncher'
function Mainfunc() {
global.app= AppLauncher()
global.app.start('index')
}
AppLauncher.js
function AppLauncher() {
function start(opts){
console.log('functions start called with' + opts)
}
}
export default AppLauncher
I want to assign the AppLauncher function as global, and call the start function nested inside it
Constructors are the way to go. You can do something like this:
// AppLauncher.js
function AppLauncher() {
// run some code...
// notice `this`
this.start = function(opts) {
console.log('start function called with', opts);
}
}
export default AppLauncher;
In your main function, call it with the new keyword:
import AppLauncher from './AppLauncher';
function Mainfunc() {
global.app = new AppLauncher();
global.app.start('index');
}
Constructors can also be written as classes (you can use it the same way as in my last example):
class AppLauncher {
constructor() {
// Anything in here gets executed when once you create an object from this class with the `new` keyword
}
// Instead of `this` we add a method to the class:
start(opts) {
console.log('start function called with', opts);
}
}
export default AppLauncher;
More about constructors: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/constructor
If you don't want to use a constructor, you can also return an object:
// AppLauncher.js
function AppLauncher() {
// Some code here...
return {
start(opts) {
console.log("function start called with", opts);
}
};
}
export default AppLauncher;
And you can use this just like you thought:
import AppLauncher from `./AppLauncher`;
function Mainfunc() {
global.app = AppLauncher();
global.app.start('index');
}
As a side note, it's conventional to call constructors with PascalCase, while regular functions are called with camelCase.

Why does function b below (in Node JS) skip iterations? [duplicate]

This question already has answers here:
What is the purpose of the var keyword and when should I use it (or omit it)?
(19 answers)
Closed 2 years ago.
I was looking into how Node JS executes code. If I set the 'sleep' parameter to 1 in both functions it works as expected.
But with different delays in the two functions, it skips iterations for the function with the longest delay.
I would expect function b to log all numbers from 0 to 99 but slower than function a.
See the code in mycompiler.io
a()
b()
async function a() {
for (n=1; n<100; n++) {
console.log('a', n)
await sleep(1)
}
}
async function b() {
for (n=1; n<100; n++) {
console.log('b', n)
await sleep(3)
}
}
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
})
}
As #CertainPerformance mentioned in the comment you must declare your variable if you want your for loops to perform correctly here. for(let n=1; n<100; n++)
Sine you're not running node in strict mode, those n variables are now essentially referencing a single shared variable, so you should notice, there are actually no numbers getting skipped, rather both functions are creating a single shared iteration from 1 to 99.
Here's what a working version of this looks like:
'use strict'
a()
b()
async function a() {
for (let n=1; n<100; n++) {
console.log('a', n)
await sleep(1)
}
}
async function b() {
for (let n=1; n<100; n++) {
console.log('b', n)
await sleep(3)
}
}
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
})
}
To echo again what was said in the comments, had you run your script in strict mode this error would have been thrown when you ran the code:
ReferenceError: n is not defined

How to Create a function in Node.js

I am using Firebase function to create an API and at the same time I Am using the Firebase Firestore as my database.
I am using Node.js to create the program.
I wanted to know how to create a function in Node.js.
I will be calling a code more than once and since I have been use to Java and Java has molecularity will it be possible in Node.js also?
This is my code
exports.new_user = functions.https.onRequest((req, res) => {
var abc=``;
if(a=='true')
{
abc=Function_A();//Get the results of Function A
}
else
{
abc=Function_B();//Get the results of Function B
//Then Call Function A
}
});
As shown in the code I would be calling the same function two times from different location depending upon the situation and then utilizing the result of it.
Is it possible to declare a function and then call if from different locations and then utilize its result?
Any help would be really appreciated as I am new to Node.js
If you are trying to just get a value back from the function it depends if you are doing synchronous (adding 2 numbers together) or asynchronous (doing an HTTP call)
synchronous:
let abc = 0;
if(a=='true')
{
abc = Function_A();//Get the results of Function A
}
else
{
abc = Function_B();//Get the results of Function B
//Then Call Function A
}
function Function_B() {
return 2+2;
}
function Function_A() {
return 1+1;
}
asynchronous:
let abc = 0;
if(a=='true')
{
Function_A(function(result) {
abc = result;
});//Get the results of Function A
}
else
{
Function_A(function(result) {
abc = result;
});//Get the results of Function A
}
function Function_B(callback) {
callback(2+2);
}
function Function_A(callback) {
callback(1+1);
}
Asynchronous with variable:
let abc = 0;
Function_A(2, function(result) {
abc = result; //should by 4
});//Get the results of Function A
function Function_A(myVar, callback) {
callback(myVar * 2);
}

Resources