I have the four functions:
// NOTE: localDataStore is a function to stringify/parse an item from localStorage
function removeCookie() {
chrome.cookies.remove({"name":"v1guid","url":"http://website.com"},function (cookie){
console.log("cookie removed");
});
}
function getCookie() {
chrome.cookies.get({"url": "http://website.com", "name": "v1guid"}, function(cookie) {
console.log(cookie);
if(cookie !== null) {
console.log("getting cookie");
localDataStore.set("cookie", cookie);
console.log(localDataStore.get("cookie"));
}
});
}
function setCookie() {
var cookiedata = localDataStore.get("cookie");
chrome.cookies.set({
"url": "http://website.com",
"name": cookiedata.name,
"value": cookiedata.value,
"domain": cookiedata.domain,
"path": cookiedata.path,
"secure": cookiedata.secure,
"httpOnly": cookiedata.httpOnly,
"storeId": cookiedata.storeId}, function(cookie) {
console.log("cookietest");
console.log(JSON.stringify(cookie));
});
}
function minePosts() {
// Do a bunch of stuff
}
I am trying to get them to wait for each other to execute before moving on to the next function in the order:
getCookie();
removeCookie();
minePosts();
setCookie();
I understand this can be done with call backs but nesting 4 call backs within each other makes my code really hard to read and makes my code a lot less modular - I may be writing my call backs wrong I am not sure. I removed the callbacks for this post in hopes someone can help me do it correctly. How can I efficiently get these 4 functions to run in that order and wait for each other sequentially? I also am using JQuery and read about the command $.Deferred() but I am not sure if this would be the right practice to use it in.
Can someone please help me? I searched around the internet and couldn't find anyone with the same problem as me trying to get upwards of 4 functions to wait for each other. Thanks!
You can use callbacks or $.Deferred() to defer functions. The former approach is simplier, on the other hand the latter one is more robust, as you can use
deferred.reject()
to handle error states.1) Callbacks
etc.
2)
$.Deferred()
etc.
or chained as suggested by riovel (jQuery 1.8+)
Here's a plunker example.