gpt4 book ai didi

有异步函数调用时的Javascript同步流程

转载 作者:行者123 更新时间:2023-11-30 11:44:49 27 4
gpt4 key购买 nike

我花了一整天的时间阅读有关 jquery deferred、promise 等的内容。

我的问题很简单。

我有一个调用 4 个其他函数的函数,其中一些函数具有从服务器获取数据的异步调用。

function A() {
async call
console.log("1");
}

function B() {
normal code
console.log("2");
}

function C() {
async call
console.log("3");
}

function xyz() {
A();
B();
C();
print str;
}

预期结果是 123str。

相反,我得到 312 或 213。基本上这 3 个函数不会等待另一个函数结束。我已经尝试使用 .done 和 $.when(a).then(b),并 promise 。

但没有任何效果。谁能给我一个可行的准系统示例代码?

编辑:

function setId() {

var doc = sessionStorage.getItem("urlDoc");
var user = sessionStorage.getItem("LoggedUser");
var string = "urlDoc=" + doc + "&user=" + user;
if (sessionStorage.getItem("countId") === null) {
$.ajax({
type: 'POST',
url: 'php/findTemporaryId.php',
data: string,
success: function (data) {
sessionStorage.setItem("countId", data);
countId = sessionStorage.getItem("countId");
id = countId;
console.log("1");

},
error: function () {
alert("Server Error");
}
});
} else {
sessionStorage.setItem("countId", parseInt(sessionStorage.getItem("countId")) + 1);
countId = sessionStorage.getItem("countId");
id = countId;
console.log("1");

}

然后

 function setAuthor() {
author = sessionStorage.getItem('LoggedUser');
console.log("2");

}

然后

function getData() {
$.ajax({
type: 'POST',
url: 'php/date.php',
success: function (data) {
date = data;
console.log("3");
},
error: function () {
alert("Error");
}
});
}

我是这样称呼他们的

function saveSelectionFragment() {

setId();
setAuthor();
getData();
}

这里是 Firebug 控制台。 http://i.imgur.com/zQ0Mk4E.jpg

最佳答案

因为你没有发布任何你说你尝试过 Promises 的东西, 这是它的工作原理..

function A() {
return new Promise(function(done) {
// emulate async call with setTimeout
setTimeout(function() {
console.log("1");
done();
}, 100);
});
}

function B() {
return new Promise(function(done) {
// "normal" code
console.log("2");
done();
});
}

function C() {
return new Promise(function(done) {
// emulate async call with setTimeout
setTimeout(function() {
console.log("3");
done();
}, 100);
});
}

function xyz() {
A()
.then(B)
.then(C)
.then(function() {
// whatever this is supposed to be
//print str;
// maybe you meant..
console.log('str');
});
}

xyz();

关于有异步函数调用时的Javascript同步流程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41351627/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com