This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I have 2 separate functions, both are making a GET request.
After completing, I need to add up number from response1 with number from response2. So basically I want make 3rd function, that will add up results from previous 2 functions.
The problem is that 3rd function executes before 1st and 2nd.
I tried callbacks, but seems it's not working as expected. Below you can find a simple example and I want to understand the basics before implementing it in my code. Example with callback I tried:
function first(callback){
setTimeout(function(){
console.log(1);
}, 500);
callback()
}
function second(){
console.log(2);
}
function third(){
first(second);
}
third();
Example without callback:
function first(){
setTimeout(function(){
console.log(1);
}, 500);
}
function second(){
console.log(2);
}
function third(){
first();
second();
}
third();
https://jsfiddle.net/u8a592pz/
Currently this function executes as:
2
1
What I want to get:
1
2
Wrap the content of first in a Promise and return it. And make third as async function and use await before first()
function first(){
return new Promise(res => {
setTimeout(function(){
console.log(1);
res();
}, 500);
})
}
function second(){
console.log(2);
}
async function third(){
await first();
second();
}
third();
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I am being given the below mentioned code and asked to print the console after 3 seconds - B and C after A.
I tried
setTimeout(main(),3000);
But I get no output.
function sleep(){
}
function main(){
console.log('A');
// call after 3 sec
console.log('B');
// call after 3 sec
console.log('C');
}
}
setTimeout(main , 3000);
remove function call '( )'
How setTimeout works:
You specify the function (as a first argument) to be called after your timeout (second argument: 3000)
Generally you should pass the function by name to the setTimeout function without calling it.
setTimeout(main,3000);
setTimeout(main(), 3000) will execute main immediately because you put the () after it. Just use the name. setTimeout(main, 3000)
Also, you'll want to put your timeout on the two specific log statements you want to call later, not the whole function, or you could also log A outside of the main function and then call the main function after the timeout.
function main() {
console.log('A');
// call after 3 sec
setTimeout(() => {
console.log('B');
console.log('C');
}, 3000);
}
main();
try this
setTimeout(main,3000);
function main(a){
console.log('A');
setTimeout(function(){
console.log('B');
setTimeout(function(){
console.log('C');
}, 3000);
}, 3000);
}
You are calling the function in the first parameter of setTimeout. It is supposed to be a callback function(function definition). Just copy the code of the main function inside the setTimeout function and it will work.
The setTimeout Function is used usually with two parameters.
The callback function
Time in milliseconds
The callback function is called after a given time (second param).
This is how it is called:
const callbackFunction = () =>{
console.log("Inside callback");
}
setTimeout(callbackFunction, 2000);
OR simply
setTimeout(() =>{
console.log("Inside callback");
}, 2000);
Output (after 2 secs)
Inside callback
Above output could also be reproduced using async-await:
function sleep(time) {
return new Promise(resolve => {
setTimeout(() => {
resolve("");
}, time);
});
}
async function main() {
await sleep(0);
console.log('A');
// call after 3 sec
await sleep(3000);
console.log('B');
// call after 3 sec
await sleep(3000);
console.log('C');
}
main();
This question already has answers here:
How to call the same JavaScript function repeatedly while waiting for the function to run its course before invoking it again, using method chaining?
(3 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
Here is what I am trying to do. Not successful and gives out error. Is it possible to delay the return value, and chain functions such that 2nd one delays the return value?
a().b()
function a( )
{
var self=this;
setTimeout( function(){ return self },2000);
return null; //<<<<< this causes problem
}
function b()
{
trace("hello");
}
You can do this sort of thing with Promises and (optionally) async/await.
Something like:
function a() {
return new Promise((resolve) => {
setTimeout(() => resolve('the return value'), 2000);
})
}
function b(value) {
console.log(`from b: ${value}`);
}
a().then(b);
I have some code which can be mimicked by this situation
function abc(def){
setTimeout(1500,function(){
console.log('1');
}
def();
}
function def(){
console.log('2'}
}
I want 2 to be printed after 1 - how do I do that?
If you want a function to also be called after a delay... just put it inside the delay. I've added some extra console logs and fixed some of your code. Run the below example to see how it works.
function def() {
console.log('2 - def()');
}
function abc() {
console.log('before');
setTimeout(function() {
console.log('1');
def();
}, 1500);
console.log('after');
}
abc();
function abc(def){
setTimeout(1500,function(){
console.log('1');
def();
}
}
You can use async and await. Wrap the setTimeout(...) in a Promise and resolve Promise inside the callback passed to setTimeout.
async function abc(def){
await new Promise(res => {
setTimeout(function(){
console.log('1');
res();
},1500)
})
def();
}
function def(){
console.log('2')
}
abc(def)
setTimeout(function, milliseconds) takes a function has the first parameter and delay value (time in milliseconds) as the second parameter. You were passing them in the wrong order.
Also in your example def() was printing 2 and it was outside the setTimeout function, so it could not have possibly printed 2 after 1 (as 1 was being logged inside the setTimeout, which means it would be executed after the delay of 1.5 seconds).
The solution provided by Chris above is correct and would do what you wanted (print 2 and then 1)
I'm trying to understand callbacks and promises using very simple examples. I figured out how to rewrite an example of why you need callbacks into a working "callback form". However, I'm stuck on rewriting this into a promise
I have tried to make this work as a promise following the example here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise#Basic_Example
But I'm having some trouble making it work.
First I got this code showing why callbacks are important:
function first(){
// Simulate a code delay
setTimeout( function(){
console.log(1);
}, 500 );
}
function second(){
console.log(2);
}
first();
second();
I then rewrote this using callbacks:
function first(callback){
// Simulate a code delay
setTimeout( function(){
console.log(1);
callback();
}, 500 );
}
function second(){
console.log(2);
}
first(second);
// second();
Now I'm wondering how to rewrite this as a promise.
let first = new Promise( function (resolve, reject){
// Simulate a code delay
setTimeout( function(){
console.log(1);
resolve('success')
}, 500 );
});
function second(){
console.log(2);
}
first.then(second());
What I want it to output is first 1 and then 2, now it ouputs 2, then 1.
this is the code that should do what you're asking.
The problem in your code is that you're actually calling second() immediately:
first.then(second());
instead of passing the function as the argument (then() will call it when the first promise is resolved):
let first = new Promise( function (resolve, reject){
// Simulate a code delay
setTimeout( function(){
console.log(1);
resolve('success')
}, 500 );
});
function second(){
console.log(2);
}
first.then(second);
So I was doing some practice about callback function and I wanted to try it out in my own was and use it with a setTimeout Method and to my surprise, it didn't work as expected.. Pls what am i doing wrong here.
function first(number, callback) {
setTimeout(function() {
console.log(number);
}, 5);
callback();
}
function second() {
console.log(2);
}
first(1, second);
You're executing setTimeout and callback at the same time. Because JavaScript is single-threaded, it doesn't wait for setTimeout to complete before executing the next statement.
That's why, 2 prints immediately, and then 1 prints after a delay of 5 milliseconds.
If you want to print 1 first, then you need to call the callback function in the callback of setTimeout. This ensures that the console.log(number) executes prior to calling the callback (which prints 2).
function first(number, callback) {
setTimeout(function() {
console.log(number);
callback();
}, 5);
}
function second() {
console.log(2);
}
first(1, second);
As 31piy already said, setTimeout() and callback() are being executed at the same time. Your code first schedules a function execution at 5ms from now, and then immediately runs another function that logs 2 to the console.
You can achieve the expected result in a couple of similar ways, I'll show one:
function first(number,callback) {
setTimeout(function() {
callback();
}, 5);
console.log(number);
}
function second() {
console.log(2);
}
first(1, second);
//Here, you immediately print the number 1 and schedule the number 2.