我有四个功能:
// 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
}
我试图让它们等待彼此执行,然后再继续按顺序执行下一个函数:
getCookie();
removeCookie();
minePosts();
setCookie();
我知道这可以通过回调来完成,但是相互嵌套 4 个回调会使我的代码非常难以阅读,并且使我的代码模块化程度降低很多 - 我不确定我可能写错了回调。我删除了这篇文章的回调,希望有人能帮助我正确地做到这一点。如何有效地让这 4 个函数按顺序运行并按顺序相互等待?我也在使用 JQuery 并阅读了命令 $.Deferred() 但我不确定这是否是使用它的正确做法。
有人可以帮我吗?我在互联网上搜索,找不到与我有同样问题的人,试图让 4 个以上的函数相互等待。谢谢!
最佳答案
您可以使用回调或 $.Deferred() 来延迟函数。前一种方法更简单,而后一种方法更健壮,因为您可以使用 deferred.reject() 来处理错误状态。
1) 回调
function removeCookie(callback) {
chrome.cookies.remove({"name":"v1guid","url":"http://website.com"},function (cookie){
console.log("cookie removed");
callback();
});
}
等等
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();
}
等等
getCookie().then(function(){
removeCookie().then(function(){
minePosts().then(function(){
setCookie().then(function(){
// do something
});
});
});
});
或按照 riovel (jQuery 1.8+) 的建议链接
getCookie()
.then(removeCookie)
.then(minePosts)
.then(setCookie)
.then(function(){
// do something
});
关于JavaScript:4 个异步函数在继续之前按顺序等待彼此完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25269703/