Calling asynchronous functions from an array [duplicate] - javascript

This question already has answers here:
Resolve promises one after another (i.e. in sequence)?
(36 answers)
How to execute promises sequentially, passing the parameters from an array?
(9 answers)
How to chain execution of array of functions when every function returns deferred.promise?
(7 answers)
Closed 2 years ago.
PromisesInSeries function that takes an array of asynchronous functions and sequentially (the next one starts when the previous one has finished) calls them, passing the result of calling the previous function as arguments
function promisesInSeries(asyncFns) {
let result;
return new Promise((resolve, reject) => {
for(const fn of asyncFns){
resolve(fn)
.then(data => fn(data))
}
})
}
I only get the results of the first function. How to call all functions from an array and, as a result, return the last value?

Without async/await you could reduce the fns array:
function promisesInSeries(fns) {
return fns.reduce((promise, fn) => promise.then(fn), Promise.resolve());
}
The first fn will receive the value undefined, after that each return value is passed to the next function.
If you want to have some initial value, you can provide it by changing Promise.resolve() to Promise.resolve(initialData). Where initialData could be a static value or a value passed through function parameters.

If you can use async-await, this is way easier:
async function promisesInSeries(asyncFns) {
let result;
for (const fn of asyncFns) {
result = await fn(result);
}
}

Related

Arrow Function Declaration | Redux | => [duplicate]

This question already has answers here:
What do multiple arrow functions mean in JavaScript?
(7 answers)
Closed 12 months ago.
Why do we have => twice. Not able to understand the arrow function declaration.
const asyncFunctionMiddleware = storeAPI => next => action => {
// If the "action" is actually a function instead...
if (typeof action === 'function') {
// then call the function and pass `dispatch` and `getState` as arguments
return action(storeAPI.dispatch, storeAPI.getState)
}
// Otherwise, it's a normal action - send it onwards
return next(action)
}
asyncFunctionMiddleware takes one argument storeAPI and returns an unnamed function. This unnamed function takes one argument next and returns another unnamed function. This unnamed function takes one argument action and returns a value.

How to use promise on callback from proprietary software [duplicate]

This question already has answers here:
How to "await" for a callback to return?
(5 answers)
How do I convert an existing callback API to promises?
(24 answers)
Closed last year.
I'm using a software that lets me read a data on it's server using this function :
webMI.data.read(nodeID, function(e){...})
Passes a current property object for every data variable specified by its nodeID to the callback function. You can pass a single nodeID or an array of nodeIDs.
In the callback i get the value i want, but i couldn't get it out and didn't want to make a callback hell
After some reading/testing on asyncronous function, i tried using promise but i keep getting the same error and i don't understand why
webMI.data.read("AGENT.OBJECTS.motor.isActive",e => e.value)
.then(result => {
console.log(result)
})
Uncaught TypeError: webMI.data.read(...) is undefined
I also tried to put it in an async function and using await
async function GetValue(){
var temp = await webMI.data.read("AGENT.OBJECTS.motor.isActive",function(e){return e.value})
return temp
}
But temp always return a Promise with state = fullfilled and value = undefined
My goal is to get 1 to X values this way to make a formula
Note that i have no way to modify 'webMI.data.read'
Use the promise constructor and resolve from within the callback
function GetValue(){
return new Promise(resolve => {
webMI.data.read("AGENT.OBJECTS.motor.isActive",function(e){resolve(e.value)})
})
}
Now the GetValue function is async, as it returns a promise and can be awaited.
How to "await" for a callback to return?

Await fetch not working as expected in Javascript [duplicate]

This question already has answers here:
async/await implicitly returns promise?
(5 answers)
Async function returning promise, instead of value
(3 answers)
Closed 1 year ago.
Why output from code below is PromiseĀ {<pending>} instead of Response.
What I doing wrong? Also await fetch("https://...") not working.
function asynchronousFunction() {
return fetch("https://thatcopy.pw/catapi/rest/")
}
const mainFunction = async () => {
const result = await asynchronousFunction()
return result;
}
console.log(mainFunction())
You shouldn't think of Promises and async functions (which return Promises) as something you can use to return a value at top-level. It's usually a bad idea that comes from the imperative and synchronous programming mindset.
Use chaining instead, either move the console.log inside mainFunction, or write this:
asynchronousFunction()
.then(console.log)

What is the purpose of the 3rd parameter (array) in a forEach callback? [duplicate]

This question already has answers here:
Why provide an array argument in Javascript's array.forEach callback?
(2 answers)
Closed 1 year ago.
I know that forEach in JavaScript calls my callback function with three parameters:
arr.forEach(function callback(currentValue, index, array) {
//your iterator
})
In the above example arr and array are same array and arr exists in the callback function closure.
Now the question is what is the point of passing array to the callback function?
If your callback function were declared elsewhere:
function forEachCallback(value, i, array) {
// ...
}
Then it has no idea what array it's being used for:
someArray.forEach(forEachCallback);
Because the array is passed as the last argument, such a callback has access to it.
The callback need not be in the same scope as the forEach call. In a case like this, the third parameter would ensure that the callback has some reference to that array.

Promises Help - Returning Values [duplicate]

This question already has answers here:
setting a variable to get return from call back function using promise
(2 answers)
How to return value from an asynchronous callback function? [duplicate]
(3 answers)
Closed 8 years ago.
I have a javascript function where I want to return the value that I get after the return method.
Easier to see than explain
function getValue(file){
var val;
lookupValue(file).then(function(res){
val = res.val;
}
return val;
}
What is the best way to do this with a promise. As I understand it, the return val will return before the lookupValue has done it's then, but the I can't return res.val as that is only returning from the inner function.
Use a pattern along these lines:
function getValue(file) {
return lookupValue(file);
}
getValue('myFile.txt').then(function(res) {
// do whatever with res here
});
(although this is a bit redundant, I'm sure your actual code is more complicated)
The best way to do this would be to use the promise returning function as it is, like this
lookupValue(file).then(function(res) {
// Write the code which depends on the `res.val`, here
});
The function which invokes an asynchronous function cannot wait till the async function returns a value. Because, it just invokes the async function and executes the rest of the code in it. So, when an async function returns a value, it will not be received by the same function which invoked it.
So, the general idea is to write the code which depends on the return value of an async function, in the async function itself.

Categories

Resources