async and await for calling couple of setTimeout in order - javascript

If I have this two variables with setTimeouts:
var printOne = setTimeout(function() {
console.log("one!");
}, 500);
var printTwo = setTimeout(function() {
console.log("two!");
}, 50);
it's just for example. What I want is, to make a function(with async and await that will call the above variables, but in order. Like this:
theFunction(printOne, printTwo);
// Will output:
// one!
// two!

To accomplish that with async functions, you need to work along with promises.
An alternative is wrapping both setTimeout calls into a function which returns a promise:
var printOne = function() {
return new Promise(function(resolve) {
setTimeout(function() {
console.log("one!");
resolve();
}, 500);
})
}
var printTwo = function() {
return new Promise(function(resolve) {
setTimeout(function() {
console.log("two!");
resolve();
}, 50);
})
}
function theFunction(one, two) {
}
async function main() {
theFunction(await printOne(), await printTwo());
}
main();

Create a function that return promise which encapsulate setTimeout
var fnPromiseTimeout = async function(msg, time) {
return new Promise( (resolve) => setTimeout( () => {
//console.log(msg);
resolve(msg);
}, time ) );
};
Demo
var fnPromiseTimeout = async function(msg, time) {
return new Promise( (resolve) => setTimeout( () => {
//console.log(msg);
resolve(msg);
}, time ) );
};
async function f1(timer1, timer2)
{
console.log("start");
var a = await timer1;
console.log(a);
var b = await timer2;
console.log(b);
console.log("end");
}
f1(fnPromiseTimeout("one", 500), fnPromiseTimeout("two", 500));

Related

async function is not waiting at await

I need to scroll down before doing some action. my promise function is not waiting in await line. how can I solve this problem?
let scrollingPromise = new Promise(async (resolve, reject) => {
// I need this part to be done before resolving
await page.evaluate(() => {
const scrollingWindow = document.querySelector('.section-layout.section-scrollbox.scrollable-y.scrollable-show');
var scrollCount = 0;
function scrollFunction(){
setTimeout(()=>{
scrollingWindow.scrollBy(0, 5000);
scrollCount++;
if(scrollCount < 5){
scrollFunction();
}
}, 3000);
};
scrollFunction();
});
// but it resolves instantly doesn't wait for previous await
resolve();
});
//this .then() runs before my scrolling
scrollingPromise.then(async () => {
// ...
}
You're mixing await and Promise syntaxes. You're awaiting an asynchronous function that doesn't return a Promise, so it can't work. I believe you're trying to do this :
let scrollingPromise = new Promise((resolve, reject) => {
page.evaluate(() => {
const scrollingWindow = document.querySelector('.section-layout.section-scrollbox.scrollable-y.scrollable-show');
var scrollCount = 0;
function scrollFunction() {
setTimeout(() => {
scrollingWindow.scrollBy(0, 5000);
scrollCount++;
if (scrollCount < 5) {
scrollFunction();
} else {
resolve() // <-- Done, resolve here
}
}, 3000);
};
scrollFunction();
});
});

How to call an asynchronous JavaScript function?

Can anyone please help me with the following, I am new to Async\Await in Javascript:
I have a trivial class:
function Thing()
{
}
Thing.prototype.ShowResult = function ()
{
var result = this.GetAsync();
alert(result);
}
Thing.prototype.GetAsync = async function ()
{
var result = await this.AsyncFunc();
return result;
}
Thing.prototype.AsyncFunc = async function ()
{
return new Promise(resolve => {
setTimeout(() => {
resolve(6);
}, 2000);
});
}
I call it like this:
var thing = new Thing();
thing.ShowResult();
I expected a delay of 2 seconds before seeing the result of 6.
Instead I immediately see:
[object Promise]
How can I correctly await the result? Thanks for any help.
You have to make the parent function consuming the async function async as well.
function Thing() {}
Thing.prototype.ShowResult = async function() { // add async
var result = await this.GetAsync(); // await the response
alert(result);
}
Thing.prototype.GetAsync = async function() {
var result = await this.AsyncFunc();
return result;
}
Thing.prototype.AsyncFunc = async function() {
return new Promise(resolve => {
setTimeout(() => {
resolve(6);
}, 2000);
});
}
Then you can call ShowResult
var thing = new Thing();
await thing.ShowResult();
But, if you're calling thing.ShowResult outside of an async function you'll have to use the Promise syntax since you can't await something that isn't in an async function. There's no concept of a "top level await" in JS. Yet.
var thing = new Thing();
thing.ShowResult().then( result => console.log(result) );
In JavaScript, async functions always return a Promise (this is why you see [object Promise]), which can be resolved either by calling its then method or by using the await keyword. For now, await can only be used inside async functions.
To apply this to your problem, you can do one of the following:
#1
Thing.prototype.ShowResult = function ()
{
this.GetAsync().then(alert);
}
thing.ShowResult();
#2
In this approach, ShowResult is also an async function. So what I wrote above also applies to it.
Thing.prototype.ShowResult = async function ()
{
var result = await this.GetAsync();
}
await thing.ShowResult();
Though AsyncFunc and GetAsync are async functions. ShowResult function is not. It is necessary for the parent function to be async as well. The below code returns 6.
function Thing()
{
}
Thing.prototype.ShowResult = async function ()
{
var result = await this.GetAsync();
alert(result);
}
Thing.prototype.GetAsync = async function ()
{
var result = await this.AsyncFunc();
return result;
}
Thing.prototype.AsyncFunc = async function ()
{
return new Promise(resolve => {
setTimeout(() => {
resolve(6);
}, 2000);
});
}
var thing = new Thing();
thing.ShowResult();
Your function GetAsync() return a promise to consume the promise you have to either use await or .then read more about async/await
function Thing() {}
Thing.prototype.ShowResult = async function() {
var result = await this.GetAsync();
alert(result);
}
Thing.prototype.GetAsync = async function() {
var result = await this.AsyncFunc();
return result;
}
Thing.prototype.AsyncFunc = async function() {
return new Promise(resolve => {
setTimeout(() => {
resolve(6);
}, 2000);
});
}
var thing = new Thing();
thing.ShowResult();
using .then
function Thing() {}
Thing.prototype.ShowResult = async function() {
var result = this.GetAsync().then((result)=>alert(result));
}
Thing.prototype.GetAsync = async function() {
var result = await this.AsyncFunc();
return result;
}
Thing.prototype.AsyncFunc = async function() {
return new Promise(resolve => {
setTimeout(() => {
resolve(6);
}, 2000);
});
}
var thing = new Thing();
thing.ShowResult();

Wait for a functions to finish in sequence Javascript

I have three functions prints 20,30,10 as per setTimeout how should i make them print 10,20,30 order using promise
How to write these callbacks to print right order.
P.S. : This is not a duplicate question. Thanks !
var A = function(callback) {
setTimeout(function() {
console.log(10)
callback();
}, 2000);
};
var B = function(callback) {
console.log(20);
callback();
};
var C = function(callback) {
setTimeout(function() {
console.log(30)
callback();
}, 200);
};
function runTask() {
var wait = ms => new Promise ((resolve,reject) => setTimeout(resolve, ms))
var FuncA = wait();
FuncA.then(() => A(function () {}))
. then(() => B(function () {}))
.then(() => C(function () {}));
}
runTask();
I'm not 100% sure I understood your question. But, here it is based on what I understood. You weren't doing anything with the callback so I didn't pass them.
In your code function B didn't have a delay.
function delayAsync(ms) {
return new Promise(p_resolve => setTimeout(p_resolve, ms));
}
async function A(callback) {
await delayAsync(2000);
console.log(10);
if (callback instanceof Function) {
callback();
}
}
async function B(callback) {
console.log(20);
if (callback instanceof Function) {
callback();
}
}
async function C(callback) {
await delayAsync(200);
console.log(30);
if (callback instanceof Function) {
callback();
}
}
function runTask() {
return new Promise(async (resolve, reject) => {
await A();
await B();
await C();
resolve();
});
}
runTask().then(() => console.log('done'));
If you want to stick with Promises, you could create a helper function that performs a setTimeout but returns a Promise. This will preserve the order of console logs:
const setTimeoutAsync = (fn, ms) => new Promise(resolve => setTimeout(() => resolve(fn()), ms));
var A = function(callback) {
return setTimeoutAsync(() => {
console.log(10)
callback();
}, 2000);
};
var B = function(callback) {
console.log(20)
callback();
};
var C = function(callback) {
return setTimeoutAsync(() => {
console.log(30)
callback();
}, 200);
};
function runTask() { // refactored since A now returns a Promise
return A(() => {})
.then(() => B(() => {}))
.then(() => C(() => {}));
}
runTask();
Alternatively, if you'd like a clean solution and don't mind adding a third party module, you could use async-af, a library for chainable asynchronous JavaScript methods that I maintain:
const setTimeoutAsync = (fn, ms) => new Promise(resolve => setTimeout(() => resolve(fn()), ms));
var A = function(callback) {
return setTimeoutAsync(() => {
console.log(10)
callback();
}, 2000);
};
var B = function(callback) {
console.log(20)
callback();
};
var C = function(callback) {
return setTimeoutAsync(() => {
console.log(30)
callback();
}, 200);
};
// to run in parallel you would omit `series`, but
// since you want to run the tasks in order include it:
function runTask(...tasks) {
return AsyncAF(tasks).series.forEach(task => task(() => {}));
}
runTask(A, B, C);
<script src="https://unpkg.com/async-af#7.0.11/index.js"></script>

How to wait a Promise inside a forEach loop

I'm using some Promises to fetch some data and I got stuck with this problem on a project.
example1 = () => new Promise(function(resolve, reject) {
setTimeout(function() {
resolve('foo1');
}, 3000);
});
example2 = () => new Promise(function(resolve, reject) {
setTimeout(function() {
resolve('foo2');
}, 3000);
});
doStuff = () => {
const listExample = ['a','b','c'];
let s = "";
listExample.forEach((item,index) => {
console.log(item);
example1().then(() => {
console.log("First");
s = item;
});
example2().then(() => {
console.log("Second");
});
});
console.log("The End");
};
If I call the doStuff function on my code the result is not correct, the result I expected is shown below.
RESULT EXPECTED
a a
b First
c Second
The End b
First First
Second Second
First c
Second First
First Second
Second The End
At the end of the function no matter how I try, the variable s gets returned as "", I expected s to be "c".
It sounds like you want to wait for each Promise to resolve before initializing the next: you can do this by awaiting each of the Promises inside an async function (and you'll have to use a standard for loop to asynchronously iterate with await):
const example1 = () => new Promise(function(resolve, reject) {
setTimeout(function() {
resolve('foo1');
}, 500);
});
const example2 = () => new Promise(function(resolve, reject) {
setTimeout(function() {
resolve('foo2');
}, 500);
});
const doStuff = async () => {
const listExample = ['a','b','c'];
for (let i = 0; i < listExample.length; i++) {
console.log(listExample[i]);
await example1();
const s = listExample[i];
console.log("Fisrt");
await example2();
console.log("Second");
}
console.log("The End");
};
doStuff();
await is only syntax sugar for Promises - it's possible (just a lot harder to read at a glance) to re-write this without async/await:
const example1 = () => new Promise(function(resolve, reject) {
setTimeout(function() {
resolve('foo1');
}, 500);
});
const example2 = () => new Promise(function(resolve, reject) {
setTimeout(function() {
resolve('foo2');
}, 500);
});
const doStuff = () => {
const listExample = ['a','b','c'];
return listExample.reduce((lastPromise, item) => (
lastPromise
.then(() => console.log(item))
.then(example1)
.then(() => console.log("Fisrt"))
.then(example2)
.then(() => console.log('Second'))
), Promise.resolve())
.then(() => console.log("The End"));
};
doStuff();
If you want NOT to wait for each promise to finish before starting the next;
You can use Promise.all() to run something after all your promises have resolved;
example1 = () => new Promise(function(resolve, reject) {
setTimeout(function() {
resolve('foo1');
}, 3000);
});
example2 = () => new Promise(function(resolve, reject) {
setTimeout(function() {
resolve('foo2');
}, 3000);
});
doStuff = () => {
const listExample = ['a','b','c'];
let s = "";
let promises = []; // hold all the promises
listExample.forEach((item,index) => {
s = item; //moved
promises.push(example1() //add each promise to the array
.then(() => {
console.log(item); //moved
console.log("First");
}));
promises.push(example2() //add each promise to the array
.then(() => {
console.log("Second");
}));
});
Promise.all(promises) //wait for all the promises to finish (returns a promise)
.then(() => console.log("The End"));
return s;
};
doStuff();

What's the right way for handling Async functions for loading a .gif image?

For example, look at this code:
function myPromise() {
return new Promise(resolve => {
setTimeout(() => {
resolve('Stack Overflow');
}, 2000);
});
}
async function sayHello() {
const externalFetchedText = await myPromise();
console.log('Hello ' + externalFetchedText);
}
sayHello();
What's the right way for showing a (.gif image file) loading before the request and hide this after Promise is resolved and the process is finished?
Most of time promises are abstracted into seprated module and are independent. So you should never do any other operation than async operation in the promises. You can show your gif while resolving the promises. See below code to show animation after you make async call, and hide it after resolution. You also have to handle reject scenario via try/catch/finally block.
function myPromise() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Stack Overflow');
// reject('Some Error')
}, 2000);
});
}
function showSpinner() {
document.getElementById('loader').style.display = 'block';
}
function hideSpinner() {
document.getElementById('loader').style.display = 'none';
}
async function sayHello() {
try {
showSpinner()
const externalFetchedText = await myPromise();
console.log('Hello ' + externalFetchedText);
} catch (err) {
console.error(err);
} finally {
hideSpinner()
}
}
sayHello();
<img id="loader" style="display:none" src="http://chimplyimage.appspot.com/images/samples/classic-spinner/animatedCircle.gif" />
You can do it in the promise if you want all the calling code that uses this promise to display the loading animation.
function myPromise() {
return new Promise(resolve => {
// Show image
setTimeout(() => {
// Hide image
resolve('Stack Overflow');
}, 2000);
});
}
async function sayHello() {
const externalFetchedText = await myPromise();
console.log('Hello ' + externalFetchedText);
}
sayHello();
function myPromise() {
return new Promise((resolve, reject) => {
setTimeout(() => {
//resolve('Stack Overflow');
reject('hello world');
}, 2000);
});
}
const newPromise = myPromise().then(result => {
"hide here"
return result;
}).catch(error => {
"hide here"
return error
});
async function sayHello() {
const externalFetchedText = await newPromise;
console.log('Hello ' + externalFetchedText);
}
sayHello();

Categories