I want to get data from db for several times. How to set a loop to execute getData() function in interval like 200ms. And if one of them success, rest of them won't be triggered. It's asynchronous method, and different from question here: Asynchronous Process inside a javascript for loop
for(var i = 0; i < 3; i++){
setTimeout(getData,200);}
This will end up with the output time interval is very close instead of 200ms, since they are asynchronous. Three "setTimeout" are triggered in a short time. like 0.001s 0.002s 0.003s, the output time is 0.201, 0.202, 2.203.
getData() returns a promise. But it can be normal function as long as it works.
You can do this by waiting for the setTimeout to finish before executing the next setTimeout
I don't believe this is possible with callbacks, as is the case with setTimeout, so you should transform it into a promise-based call
const promiseSetTimeout = timeout => new Promise(r => setTimeout(r, timeout));
const waitManyTimes = async () => {
for(let i = 0; i < 3; i++) {
await promiseSetTimeout(200);
// do something here, like getDB
console.log(i);
}
}
waitManyTimes();
Don't use a loop. Have the function call setTimeout() to run itself again if it fails.
var i = 0;
function callGetDB() {
getDB().then(db => {
// use DB
}).catch(() => {
if (i++ < 3) {
setTimeout(callGetDB, 200);
}
});
}
I'm assuming the asynchronous function getDB() returns a promise.
Using async/await:
let sleep = ms => new Promise(r => setTimeout(r, ms));
let main = async() => {
for(var i = 0; i < 3; i++) {
let db = getDB();
if (db)
return db;
await sleep(200);
}
};
Related
I have two for loop, inside them I have setTimeout function like following code:
for(let i=0;i<3;i++){
setTimeout(()=>{console.log(i)}, 1000)
}
for(let i=0;i<3;i++){
setTimeout(()=>{console.log(i)}, 1000)
}
i want the second loop does not executed until after the first loop finished,
I want this result:
0
1
2
0
1
2
- and between 2 numbers wait 1 second.
how i can do that?
I can't comment yet or I would ask clarifying questions so I'll give you what I think you're asking for. If you want a 1 second delay between each number being logged to the console then this will work:
const func = async () => {
for (let i = 0; i < 3; i++) {
await new Promise((resolve) =>
setTimeout(() => {
console.log(i);
resolve();
}, 1000)
);
}
for (let i = 0; i < 3; i++) {
await new Promise((resolve) =>
setTimeout(() => {
console.log(i);
resolve();
}, 1000)
);
}
};
func();
A quick rundown of what's happening here. I created an outer function named func which I made asynchronous so that I can use the await keyword within it. I then put the setTimeout call inside a new instance of Promise. The promise combined with the await means that javascript will essentially stop at that line until the Promise calls resolve. Once resolve is called that instance of Promise is finished and the await statement stops "blocking" javascript and the callbackque continues.
TLDR:
To use await you must be in an asynchronous function.
If await is used in front of a Promise everything will stop until the promise resolves.
Placing the resolve of the promise inside the callback given to setTimeout ensures that we will wait until each timeout finishes BEFORE the next timeout begins.
This will work
nxt (0, 0);//seed the stack
function nxt(num, itertn){
if(num == 3){//want till 2
if(itertn == 0){// first or 2nd iteration
num =0;
itertn++;
}else{
return;//after 2nd stop
}
}
console.log(num);//the work
num++;
setTimeout(nxt, 1000, num, itertn);//next after a second
}
But there are other ways to do this
I think that you're trying to do sort of a counter
Try something like this:
for(let i=1;i<=3;i++){
setTimeout(()=>{ console.log(i)}, i*1000 )
}
Let me know if this solve your problem
Try nested loop
for(let i=0;i<2;i++){
for(let j=0;j<3;j++){
setTimeout(()=>{console.log(j)}, 1000)
}
}
One solution is create promises, and with map and promise.all, you can group each loop of promises and execute them sequentially.
(async () => {
const second = (i) => new Promise(resolve => setTimeout(() => {
console.log(i)
resolve(i)
}, 1000))
const loop = () => Array(3).fill(0).map(async(item, index) => {
return await second(index)
})
var startTime = performance.now()
await Promise.all(loop())
var endTime = performance.now()
console.log(endTime - startTime)
await Promise.all(loop())
endTime = performance.now()
console.log(endTime - startTime)
})()
How can I call method with queue?
Let say I have a method, this method will call the API and it needs to handle only 3 call at a time. When more than 3 calls from some component. It needs to wait until any of the call finish and run the next
This is just illustration, I don't loop API call, the real project is call API by user action
for (let i = 0; i < 9; i++) {
doSomething(i)
}
doSomething(param){
//call api
}
It should call doSomething 0 - 9, but I want to call api for the first 3, and the other will wait until any of the call is finished
Try using Promise and async functions for the implementation.
A sample implementation.
for (let i = 0; i < 9; i++) {
doSomething(i)
}
async function doSomething(param) {
//call api
if ( param < 3 ) {
const x = callApi();
console.log(x);
} else {
const x = await callApi();
console.log(x);
}
}
async function callApi() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('success')
}, 2000)
})
}
I am unsure how the usage of returning a new Promise vs using a Promise.resolve() and want to make sure my understanding of these are correct.
Given these 3 functions below:
function testFunc() {
return Promise.resolve().then(() => {
//anything asynchronous in here has now become synchronous and
//execution of result of the function happens after this??
let i = 0;
while (i < 10000) {
console.log(i);
i++;
}
});
}
------
function testFunc2() {
return new Promise((resolve, reject) => {
//anything asynchronous in here is still asynchronous but the
//`resolve()` is then synchronous??
let i = 0;
while (i < 10000) {
if (i === 999) { resolve('I am a test func') };
i++;
}
})
}
------
//synchronous function
function logMe() {
let i = 0;
while (i < 10000) {
console.log("INSIDE LOG ME);
i++;
}
}
The way I understand it is that testFunc() immediately resolves the Promise and anything within there becomes synchronous. So if you were to execute:
testFunc();
logMe();
testFunc() would fully execute before logMe() was reached and executed.
For the testFunc2(), if it were executed in this order:
testFunc2();
logMe();
I understand it as the logic inside, in this case the while loop, would still execute synchronously and delay the execution of the following function, logMe(), but the resolve would be treated asynchronously.
It’s not that easy. You would have to use test Func.then(logMe()). Another option would be to run both functions in an asynchronous function:
async function run() {
await testFunc();
logMe();
}
The await is pretty simple - it runs the function and waits for it to finish, then runs the next lines. async is just there so that await can work (await does not work outside of async functions).
I prefer async/await, but many more prefer .then. It’s just what you want to use, both are very similar.
If I understand correctly what you're trying to achieve, you want to asynchronously execute operation inside the loop.
function testFunc2() {
const promises = []
for(let i = 0; i<1000; i++){
promises.push(new Promise((resolve) => {
console.log(i);
resolve()
}));
}
return Promise.all(promises);
}
function logMe() {
let i = 0;
while (i < 5) {
console.log("INSIDE LOG ME");
i++;
}
}
(async() => {
await testFunc2()
logMe();
})();
I made a mistake in the previous question, causing the respondent to fail to understand what I meant. So I asked a new question again.
I need to handle multiple asynchronous operations in a loop. These asynchronous operations I use await to let them execute serially. The result I want is that loops are parallel, asynchronous operations in each loop run serially, but the result is all stringed up. How to resolve this situation?
In each loop, I use await to deal with Promise ,which has asynchronous operation.But all are serial.
My code like this:
var func1 = function(){return new Promise(function(resolve, reject){
//After 10s print(1);
loadRes("resname_1",
(res)=>{print(1); resolve(res);},
(err)=>{reject(err);});
})}
var func2 = function(){return new Promise(function(resolve, reject){
//After 10s print(2);
//some async operation like above
})}
var func3 = function(){return new Promise(function(resolve, reject){
//After 10s print(3);
//some async operation like above
})}
var test = async function(){
//some code...;
await func1;
//some code...;
await func2;
await func3;
}
for(let i = 0; i < 3; ++i){
test();
}
The result I got: 111222333, total seconds: 90
What I want is: output 123 three times Simultaneously, each 123 is serial, total seconds 30.
Your code already has the expected behavior. You claim it takes 90 seconds to execute, but the code you provided would only take 30 seconds. Here's a reproduction of your code, with all the delays cut by a factor of 10 to speed things up. So this will wait one second, log 111, then wait one second, log 222, then wait one second, log 333. Total time, 3 seconds (corresponding to 30 seconds if i did the full durations)
const delay = (duration) => new Promise(resolve => setTimeout(resolve, duration));
const func1 = () => delay(1000).then(() => console.log(1));
const func2 = () => delay(1000).then(() => console.log(2));
const func3 = () => delay(1000).then(() => console.log(3));
const test = async () => {
await func1();
await func2();
await func3();
}
for(let i = 0; i < 3; ++i){
test();
}
I guess the expected behaviour is to print out :(10s)1=>(10s)2=>(10s)3=>(10s)1=>(10s)2=>(10s)3=>(10s)1=>(10s)2=>(10s)3. 123123123 in 90 seconds, right?
If so, the problem comes from the loop :
for(let i = 0; i < 3; ++i){
test();
}
It fires 3 asynchronous calls, each call fires func1() func2() func3() in order. However, the 3 asynchronous calls do not wait for each other to finish execution. For example when call A prints 1, then at the same time call B prints 1 too. So the console outputs 111222333 after 30 seconds.
To solve the problem, make the 3 asynchronous calls to be synchronous. It can be achieved by putting the loop in an asynchronous function, with await test():
const forLoop = async _ => {
for(let i = 0; i < 3; ++i){
await test();
}
}
Full example:
const sleep = ms => {
return new Promise( resolve =>
setTimeout(resolve, ms)
);
}
const func1 = function(){
//After 10s print(1);
return sleep(10000).then(_ => console.log("1"));
}
const func2 = function(){
//After 10s print(2);
return sleep(10000).then(_ => console.log("2"));
}
const func3 = function(){
//After 10s print(3);
return sleep(10000).then(_ => console.log("3"));
}
const test = async function(){
await func1();
await func2();
await func3();
}
const forLoop = async _ => {
for(let i = 0; i < 3; ++i){
await test();
}
}
forLoop();
I'm new to the concept of recursion. I've been practicing JavaScript with some codes from javascript30.com. I've stumbled upon the below mention function:
function peep() {
const time = randomTime(200, 1000);
const hole = randomHole(holes);
hole.classList.add('up');
setTimeout(() => {
hole.classList.remove('up');
if (!timeUp) peep();
}, time);
}
Link to full code: https://codepen.io/luckyseven444/pen/bXqXbP (code is running ok in my PC)
Is it possible to form a simple loop rather than the recursive function peep() mentioned above? I mean I want to replace the second peep() inside setTimeout function.
Thanks
If you really insist, you can create an async function, wrap setTimeout with a Promise, await the Promise and add a loop:
async function test() {
for (let i = 0; i < 10; i++) {
console.log('before setTimeout', i);
await new Promise(resolve => setTimeout(() => {
console.log('timeout elapsed', i);
resolve();
}, 1000));
}
}
test();