0

Here is my function

function two(){ console.log('two') } function one(callback){ setTimeout(()=>{ console.log('one') },2000) callback() } one(two) 

Actual output:

two one 

My expected Output:

one two 

My question is how to make changes to these functions so that function two() will be executed after function one()

3 Answers 3

2

You could simply call the callback() in your setTimeout's anonymous function like so:

function two() { console.log('two') } function one(callback) { setTimeout(() => { console.log('one'); callback(); // execute callback after everything in setTimeout is executed }, 2000); } one(two);

... or, instead, you can use a Promise with ES7's async/await (or using a .then() callback) capabilities like so:

function two() { console.log('two') } async function one(callback) { // make async so we can use `await` await new Promise((resolve, rej) => { // wait for the promise to resolve ... setTimeout(() => { console.log('one'); resolve(); }, 2000) }); callback(); // ... then execute the callback } one(two);

Sign up to request clarification or add additional context in comments.

Comments

1

This works

let one = new Promise((resolve, reject) =>{ setTimeout(()=>{ console.log('one') resolve(true) },2000) }) one.then((value) => { console.log('two') }) 

Comments

0

I think callback will be called before other execution.This also works.

 function two(){ console.log('two') } function one(one, callback){ console.log(one); callback() } one('one', two); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.