How to Change the Order of Functions Triggered

How can I change the order of functions triggered?

Data is loaded from Firebase asynchronously. Since that may take some time, your completion handler is called later than you might expect.

For this reason, any code that needs the data from the database, needs to be inside the completion handler, or be called from there.

So the simplest fix is to move the performSegue into the callback:

extension HomeViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

db.collection(K.FStore.newGameCpllection)
.whereField(K.FStore.uID, isEqualTo:players[indexPath.row].uID)
.addSnapshotListener { (querySnapshot, err) in
if let err = err {
print("Error getting game db: \(err)")
} else {
for doc in querySnapshot!.documents {

print("document saved!!")
self.gameDocumentID = doc.documentID
self.db.collection(K.FStore.newGameCpllection).document(self.gameDocumentID).updateData([
K.FStore.player2Field: self.playerInfo[K.FStore.nameField]!
]) { err in
if let err = err {
print("Error updating document: \(err)")
} else {
print("Document successfully updated")
}
print("segue triggered!!!")
self.performSegue(withIdentifier: K.homeToGameScreen, sender: self)
}
}

}
}
}
}

Also see:

  • Is Firebase getDocument run line by line?
  • Handling asynchronous Firestore data reading in tableView - iOS
  • Storing asynchronous Cloud Firestore query results in Swift, using a dispatch group to seemingly change the order of execution.
  • How do I save data from cloud firestore to a variable in swift?

How do you change the event firing order of the same event?

If you are using 'delegate' the way you have it in your example, then the ajax submission is always going to run first, so the short answer to your question is "You Can't". Your delegate is attached to the 'body' element, so events attached to elements closer to the form in the DOM tree will fire first.

Events bubble from the form -> body, so there is no ordering when you are doing that.

One option would be to have your verification trigger a second event.

methods.checkForm = function (e) {
e.preventDefault()

if ($(this).isVerified()) {
$(this).trigger('form-verified');
}
};

Then instead of binding the other handler to 'submit', you would bind it to 'form-verified'.

$('form').bind('form-verified', methods.submitFormIfCheckedFormIsTrue);

This is also another way to accomplish ordering event if they are attached to the same element instead of using delegate.

Also, if you are using jQuery >= 1.7, then you should be using on instead of bind and delegate. http://api.jquery.com/on/

Update

If both are bound to the same element, then they will be triggered in the order that they were attached to the element. Assuming checkForm is bound before the other one, then the issue is that return false; does not stop other events from firing if they are attached to the same element. For that you also need e.stopImmediatePropagation().

methods.checkForm = function (e) {
e.preventDefault()

if (!$(this).isVerified()) {
e.stopImmediatePropagation();
}
};

There is also a useful answer over here if you ever have to tweak the ordering of events. jQuery event handlers always execute in order they were bound - any way around this?

How to change event execution order?

Please review this one:

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<title>Close window</title>

</head>

<body>

<!-- here is your first AddEventlistener-->

<button id="abc" onclick="temp1()">button</button>

<script type="text/javascript">

function temp1() {

alert("temp1");

};

function temp2() {

alert("temp2");

}

/*then here is your second AddEventlistener*/

var d = document.getElementById("abc");

d.addEventListener("click", temp2, false);

/*javascript will execute it in order

if you want to change the order. remove first EventListener then register new one after. something like this:

*/

//remove listener

d.onclick = null;

//register new

d.addEventListener('click', temp1);

</script>

</body>

</html>

order in triggering events and functions

Just call otherFunction asynchronously:

window.addEventListener("hashchange", function() {

eventFunction();

}, false);

document.querySelector('button').addEventListener('click', function() {

location.hash = "changed";

setTimeout(otherFunction, 0);

});

function eventFunction() {

console.log('first');

}

function otherFunction() {

console.log('second');

}
<button type="button">

Click!

</button>

How should I call 3 functions in order to execute them one after the other?

In Javascript, there are synchronous and asynchronous functions.

Synchronous Functions

Most functions in Javascript are synchronous. If you were to call several synchronous functions in a row

doSomething();
doSomethingElse();
doSomethingUsefulThisTime();

they will execute in order. doSomethingElse will not start until doSomething has completed. doSomethingUsefulThisTime, in turn, will not start until doSomethingElse has completed.

Asynchronous Functions

Asynchronous function, however, will not wait for each other. Let us look at the same code sample we had above, this time assuming that the functions are asynchronous

doSomething();
doSomethingElse();
doSomethingUsefulThisTime();

The functions will be initialized in order, but they will all execute roughly at the same time. You can't consistently predict which one will finish first: the one that happens to take the shortest amount of time to execute will finish first.

But sometimes, you want functions that are asynchronous to execute in order, and sometimes you want functions that are synchronous to execute asynchronously. Fortunately, this is possible with callbacks and timeouts, respectively.

Callbacks

Let's assume that we have three asynchronous functions that we want to execute in order, some_3secs_function, some_5secs_function, and some_8secs_function.

Since functions can be passed as arguments in Javascript, you can pass a function as a callback to execute after the function has completed.

If we create the functions like this

function some_3secs_function(value, callback){
//do stuff
callback();
}

then you can call then in order, like this:

some_3secs_function(some_value, function() {
some_5secs_function(other_value, function() {
some_8secs_function(third_value, function() {
//All three functions have completed, in order.
});
});
});

Timeouts

In Javascript, you can tell a function to execute after a certain timeout (in milliseconds). This can, in effect, make synchronous functions behave asynchronously.

If we have three synchronous functions, we can execute them asynchronously using the setTimeout function.

setTimeout(doSomething, 10);
setTimeout(doSomethingElse, 10);
setTimeout(doSomethingUsefulThisTime, 10);

This is, however, a bit ugly and violates the DRY principle[wikipedia]. We could clean this up a bit by creating a function that accepts an array of functions and a timeout.

function executeAsynchronously(functions, timeout) {
for(var i = 0; i < functions.length; i++) {
setTimeout(functions[i], timeout);
}
}

This can be called like so:

executeAsynchronously(
[doSomething, doSomethingElse, doSomethingUsefulThisTime], 10);

In summary, if you have asynchronous functions that you want to execute syncronously, use callbacks, and if you have synchronous functions that you want to execute asynchronously, use timeouts.

How to trigger jQuery change event in code

Use the trigger() method

$(selector).trigger("change");

How to order events bound with jQuery

I had been trying for ages to generalize this kind of process, but in my case I was only concerned with the order of first event listener in the chain.

If it's of any use, here is my jQuery plugin that binds an event listener that is always triggered before any others:

** UPDATED inline with jQuery changes (thanks Toskan) **

(function($) {
$.fn.bindFirst = function(/*String*/ eventType, /*[Object])*/ eventData, /*Function*/ handler) {
var indexOfDot = eventType.indexOf(".");
var eventNameSpace = indexOfDot > 0 ? eventType.substring(indexOfDot) : "";

eventType = indexOfDot > 0 ? eventType.substring(0, indexOfDot) : eventType;
handler = handler == undefined ? eventData : handler;
eventData = typeof eventData == "function" ? {} : eventData;

return this.each(function() {
var $this = $(this);
var currentAttrListener = this["on" + eventType];

if (currentAttrListener) {
$this.bind(eventType, function(e) {
return currentAttrListener(e.originalEvent);
});

this["on" + eventType] = null;
}

$this.bind(eventType + eventNameSpace, eventData, handler);

var allEvents = $this.data("events") || $._data($this[0], "events");
var typeEvents = allEvents[eventType];
var newEvent = typeEvents.pop();
typeEvents.unshift(newEvent);
});
};
})(jQuery);

Things to note:

  • This hasn't been fully tested.
  • It relies on the internals of the jQuery framework not changing (only tested with 1.5.2).
  • It will not necessarily get triggered before event listeners that are bound in any way other than as an attribute of the source element or using jQuery bind() and other associated functions.

triggering function on order status change with information from product

You can't access global $product; inside woocommerce_order_status_changed or woocommerce_order_status_processing.

using woocommerce_order_status_changed action hook parameter
$order_id, $status_from, $status_to, $order

function trigerinam_i_duombaze_changed( $order_id, $status_from, $status_to, $order) {

// get order from order id
$order = wc_get_order( $order_id );

foreach ($order->get_items() as $item_id => $item ) {

$pavadinimas = $item->get_name();

$sql = "INSERT INTO garantiniai (kompiuterio_bukle, preke, uzsakymo_bukle)
VALUES ('bukle', $pavadinimas, 'processing')";
}
}
add_action( 'woocommerce_order_status_changed', 'trigerinam_i_duombaze_changed', 99, 4 );

using woocommerce_order_status_changed action hook parameter
$order_id, $order

function trigerinam_i_duombaze_processing( $order_id, $order) {

// get order from order id
$order = wc_get_order( $order_id );

foreach ($order->get_items() as $item_id => $item ) {

$pavadinimas = $item->get_name();

$sql = "INSERT INTO garantiniai (kompiuterio_bukle, preke, uzsakymo_bukle)
VALUES ('bukle', $pavadinimas, 'processing')";
}
}
add_action( 'woocommerce_order_status_processing', 'trigerinam_i_duombaze_processing', 10, 2);

Firebase Function : How to trigger Functions in order

According to the Firebase documentation, one of the limitations is that the order in which the Cloud Functions are triggered is not guaranteed. Also a single event may cause multiple Cloud Functions invocations.

A detailed explanation of a work around can be found in the How to deal with Firebase trigger function execution order. Here a community member’s workaround is to store a admin.database.ServerValue.TIMESTAMP with the list add and verify in the results calculator that it produced results for the latest timestamp. If not, it tries again.



Related Topics



Leave a reply



Submit