I have an array of functions such as:
let funcs = []
funcs.push(() => {window.x = fetch()})
funcs.push(() => {console.log(window.x)})
funcs.push(() => {console.log("Hello, world!")})
I would like the functions to be evoked one after the other, as in:
for (let func of funcs) {
func();
}
However, I would like to concatenate the functions as if they were Promises so that the N+1 function is only ever invoked when the N function is resolved.
3
Answers
Some of your functions involve asynchronous operations and you must make clear when you consider such a function "resolved". More precisely, if you want to wait for a certain result, your function must return a promise for that result. For example,
fetch
returns a promise for a response object:but you could alternatively wait for the response body to be completely consumed:
Synchronous functions like your second and third need not return anything.
With that you can use the following code to execute them one after another:
You can mix "normal" functions with functions returning promises in your
funcs
array, but you will have to make sure that the promise (if there is one …) is actuallyreturned
by the generating function and not only generated. I removed the curly braces ({
,}
) around your first function and also made sure that it returned a "sensible" value at the end (by supplying a further.then(r=>r.json()).then(d=>window.x=d.username)
to it).Once the
funcs
array is set up you can run the indivudual function consecutively in anasync
function by using theawait
keyword like this:It is generally not a good idea to work with a global variable like
window.x
. I only included it here in order to show that theoretically your approach can be made to work. However, a better way to get the result of a promise would be to return the desired value by the last chainedthen()
method and pick it up by an expression that waits for it withawait
. But, of course, then your second function would also need to be changed in order not to be working with the globalx
but with a given argumentval
:According to mdn web docs,
fetch()
will returnPromise
, so it will printHello, world!
first instead of value ofwindow.x
becausewindow.x
isPromise
. So, you must resolve the fetch response first before printing it with theasync
function like this: