If I comprehend your query (and code sample) correctly, it seems like you are aiming to
- Pause for 200 milliseconds
- Loop through a list of items. And for each item you wish to:
- Invoke a function, passing the current item and receiving a response in return.
- Wait for 1 second.
- Call another function, passing the obtained response.
To achieve this, you will require a sleep()
function that yields a promise which resolves after the specified time:
function sleep(ms = 1000) {
const p = new Promise( (resolve, reject) => {
setTimeout(() => resolve());
});
return p;
}
Next, you need an async
function to carry out the actual tasks. It must be declared as async
because it enables the use of await
:
async function process_items( items, delayInMs = 1000 ) {
for ( item of items ) {
const res = await doSomething( item, delayInMs );
await sleep(delay);
await doSomethingElse( res );
}
}
By observing the provided code snippet, you can see that utilizing async
/await
offers a more concise and declarative syntax compared to using callbacks or promise chains.
You can further encapsulate everything within another async
function:
async function myfunction() {
await sleep(200);
await process_items( this.myarray, 1000 );
}
Designating a function as async
serves two purposes: it
- Enables the utilization of
await
inside that function, and
- Transforms the function into one that returns a promise, regardless of its apparent return value.
For instance, if we consider this function:
function foo() {
return 1;
}
and modify it to become an async
function:
async function foo() {
return 1;
}
It is roughly equivalent to altering it to look like:
function foo() {
return Promise.resolve(1);
}