Efficient way of executing 2 functions one after another in Javascript - javascript

I have two functions
function one() {
setTimeout(function(){ console.log("first function executed"); }, 3000);
}
function two() {
console.log("second function executed");
}
How can i let second function waits till first function executed? What is the easiest way for a beginner? Thanx

There are a couple of ways you could approach this, the two most common ways would be using a callback, or using Promises.
Using Callbacks
You would add a callback argument to the first function, and then pass in function two as the callback:
function one(callback) {
setTimeout(function() {
console.log("first function executed");
callback();
}, 3000);
}
function two() {
console.log("second function executed");
}
one(two)
Using Promises:
Promises allow you to chain different actions together that are dependant on ordering. However, you may need to add polyfills to support older browsers:
function one() {
return new Promise(function(resolve, reject) {
setTimeout(function() {
console.log("first function executed");
resolve();
}, 3000);
})
}
function two() {
console.log("second function executed");
}
one().then(two)

Related

How to make functions execute synchronously in javascript? or how to make functions execute one after another?

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()
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);
This works
let one = new Promise((resolve, reject) =>{
setTimeout(()=>{
console.log('one')
resolve(true)
},2000)
})
one.then((value) => {
console.log('two')
})
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);

Fix error when trying to rewrite callback example to a promise

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);

Javascript execution order in asp.net

In the Master.aspx I have some init code
app.asynInit(
getData();// this needs to execute first
)
And then in one of the custom control I have some logic
doSomethingLater() // this needs to wait for the getData()
I am not sure what is the best way to make sure doSomething() always execute after app.asynInit()
My current solution is to use jQuery's custom event.
app.asynInit() // this needs to execute first
$(document).trigger('initCompleted')
$(document).on('initCompleted',function(){ document() // this needs to wait for the getData()})
It appears to work. But is there any better alternatives? Should I use document here?
You can try to use Promise class:
var initAsync = function () {
var promise = new Promise(function (done) {
setTimeout(function () {
console.log('DONE');
done();
}, 3000);
});
return promise;
};
(async function () {
await initAsync();
console.log('continue...');
// doSomething();
}());
Source: Promise
If you're using this action on IE old version. You can use callback function:
var init = function (callback) {
setTimeout(function () {
console.log('DONE');
callback();
}, 3000);
};
init(function () {
console.log('continue...');
// doSomething();
});
I end up in with this implementation with the callback approach:
In Master.aspx:
app.asynInit(
getData();// this needs to execute first
window.isDataGet = true;
)
function onDataGet(cb){
if(window.isDataGet )
cb();
else
setTimeout(onDataGet,100)
}
In Custom Control:
onDataGet(//callback function here)

Using java script promises for calling function once

var dataPromise= $q.defer();
function getDataPromise(){
return dataPromise.promise;
}
(function getData(){
setTimeOut(
function(){
myPromise.resolve("data");
}
,1000);
})();
getDataPromise().then(function(){alert("use old data");});
In this code "dataPromise" defined out of "getData" function scope, therefor new promise won't be created on each "getData" invocation.
"getData" will invoce once and "dataPromise" will hold the first invoke data, and won't be update.
I want to understand if this is promise anty-pattern? if so - what is the correct way to call async function once?
Here's how I would write it:
const dataPromise = $q(function(resolve) {
setTimeOut(function() {
resolve("data");
}, 1000);
});
function getDataPromise() {
return dataPromise;
}
getDataPromise().then(function(){alert("use old data");});

Call a function after previous function is complete

I have the following JavaScript code:
$('a.button').click(function(){
if (condition == 'true'){
function1(someVariable);
function2(someOtherVariable);
}
else {
doThis(someVariable);
}
});
How can I ensure that function2 is called only after function1 has completed?
Specify an anonymous callback, and make function1 accept it:
$('a.button').click(function(){
if (condition == 'true'){
function1(someVariable, function() {
function2(someOtherVariable);
});
}
else {
doThis(someVariable);
}
});
function function1(param, callback) {
...do stuff
callback();
}
If you're using jQuery 1.5 you can use the new Deferreds pattern:
$('a.button').click(function(){
if(condition == 'true'){
$.when(function1()).then(function2());
}
else {
doThis(someVariable);
}
});
Edit: Updated blog link:
Rebecca Murphy had a great write-up on this here: http://rmurphey.com/blog/2010/12/25/deferreds-coming-to-jquery/
Try this :
function method1(){
// some code
}
function method2(){
// some code
}
$.ajax({
url:method1(),
success:function(){
method2();
}
})
This answer uses promises, a JavaScript feature of the ECMAScript 6 standard. If your target platform does not support promises, polyfill it with PromiseJs.
Promises are a new (and a lot better) way to handle asynchronous operations in JavaScript:
$('a.button').click(function(){
if (condition == 'true'){
function1(someVariable).then(function() {
//this function is executed after function1
function2(someOtherVariable);
});
}
else {
doThis(someVariable);
}
});
function function1(param, callback) {
return new Promise(function (fulfill, reject){
//do stuff
fulfill(result); //if the action succeeded
reject(error); //if the action did not succeed
});
}
This may seem like a significant overhead for this simple example, but for more complex code it is far better than using callbacks. You can easily chain multiple asynchronous calls using multiple then statements:
function1(someVariable).then(function() {
function2(someOtherVariable);
}).then(function() {
function3();
});
You can also wrap jQuery deferrds easily (which are returned from $.ajax calls):
Promise.resolve($.ajax(...params...)).then(function(result) {
//whatever you want to do after the request
});
As #charlietfl noted, the jqXHR object returned by $.ajax() implements the Promise interface. So it is not actually necessary to wrap it in a Promise, it can be used directly:
$.ajax(...params...).then(function(result) {
//whatever you want to do after the request
});
Or you can trigger a custom event when one function completes, then bind it to the document:
function a() {
// first function code here
$(document).trigger('function_a_complete');
}
function b() {
// second function code here
}
$(document).bind('function_a_complete', b);
Using this method, function 'b' can only execute AFTER function 'a', as the trigger only exists when function a is finished executing.
you can do it like this
$.when(funtion1()).then(function(){
funtion2();
})
This depends on what function1 is doing.
If function1 is doing some simple synchrounous javascript, like updating a div value or something, then function2 will fire after function1 has completed.
If function1 is making an asynchronous call, such as an AJAX call, you will need to create a "callback" method (most ajax API's have a callback function parameter). Then call function2 in the callback. eg:
function1()
{
new AjaxCall(ajaxOptions, MyCallback);
}
function MyCallback(result)
{
function2(result);
}
If method 1 has to be executed after method 2, 3, 4. The following code snippet can be the solution for this using Deferred object in JavaScript.
function method1(){
var dfd = new $.Deferred();
setTimeout(function(){
console.log("Inside Method - 1");
method2(dfd);
}, 5000);
return dfd.promise();
}
function method2(dfd){
setTimeout(function(){
console.log("Inside Method - 2");
method3(dfd);
}, 3000);
}
function method3(dfd){
setTimeout(function(){
console.log("Inside Method - 3");
dfd.resolve();
}, 3000);
}
function method4(){
console.log("Inside Method - 4");
}
var call = method1();
$.when(call).then(function(cb){
method4();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
If function1 is some sync function that you want to turn into an async one because it takes some time to complete, and you have no control over it to add a callback :
function function1 (someVariable) {
var date = Date.now ();
while (Date.now () - date < 2000); // function1 takes some time to complete
console.log (someVariable);
}
function function2 (someVariable) {
console.log (someVariable);
}
function onClick () {
window.setTimeout (() => { function1 ("This is function1"); }, 0);
window.setTimeout (() => { function2 ("This is function2"); }, 0);
console.log ("Click handled"); // To show that the function will return before both functions are executed
}
onClick ();
The output will be :
Click handled
...and after 2 seconds :
This is function 1
This is function 2
This works because calling window.setTimeout () will add a task to the JS runtine task loop, which is what an async call makes, and because the basic principle of "run-to-completion" of the JS runtime ensures that onClick () is never interrupted before it ends.
Notice that this as funny as it makes the code difficult to understand...

Categories