简体   繁体   中英

JavaScript: 4 asyncronys functions to wait for each other sequentially to finish before continuing?

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

function removeCookie(callback) {
    chrome.cookies.remove({"name":"v1guid","url":"http://website.com"},function (cookie){
        console.log("cookie removed");
        callback();
    });
}

etc.

getCookie(function(){
    removeCookie(function(){
        minePosts(function(){
            setCookie(function(){
                // do something
            });
        });
    });
});

2) $.Deferred()

function removeCookie() {
    var deferred = $.Deferred();
    chrome.cookies.remove({"name":"v1guid","url":"http://website.com"},function (cookie){
        console.log("cookie removed");
        deferred.resolve();
    });
    return deferred.promise();
}

etc.

getCookie().then(function(){
    removeCookie().then(function(){
        minePosts().then(function(){
            setCookie().then(function(){
                // do something
            });
        });
    });
});

or chained as suggested by riovel (jQuery 1.8+)

getCookie()
    .then(removeCookie)
    .then(minePosts)
    .then(setCookie)
    .then(function(){
        // do something
    });
function one() {
  console.log('one');

  deferred = jQuery.Deferred();

  setTimeout(function() {
    console.log('one done');
    deferred.resolve();
  }, 1000);

  return deferred;
}

function two() {
  console.log('two');

  deferred = jQuery.Deferred();

  setTimeout(function() {
    console.log('two done');
    deferred.resolve();
  }, 1000);

  return deferred;
}

function three() {
  console.log('three');

  deferred = jQuery.Deferred();

  setTimeout(function() {
    console.log('three done');
    deferred.resolve();
  }, 1000);

  return deferred;
}

function four() {
  console.log('four');

  deferred = jQuery.Deferred();

  setTimeout(function() {
    console.log('four done');
    deferred.resolve();
  }, 1000);

  return deferred;
}

one()
.then(two)
.then(three)
.then(four);

Here's a plunker example .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM