【发布时间】:2017-10-16 18:20:46
【问题描述】:
基本上,我需要 2 个函数 A 和 B 来获取数据,然后我想在成功获取数据后运行函数 C
这是我的代码:
JS:
var A = function() {
$.getJSON('linkA', function(data) {
a = data.total;
console.log("A : " + a);
});
return new Promise(function(resolve, reject) {
resolve('Got a');
});
};
var B = function() {
$.getJSON('linkB', function(data) {
b = data.total;
console.log("B:" + b);
});
return new Promise(function(resolve, reject) {
resolve('Got b');
});
};
function run() {
Promise.all([A(), B()]).then(function() {
console.log("Got A and B")
});
}
HTML:
<script>
run();
</script>
我希望结果应该在控制台中:
A: //数据
B: //数据
得到A和B
但是,我仍然在其他两行之前得到了“Got A and B”。我猜是因为获取数据需要很长时间,所以程序首先编写“得到 A 和 B”。但必须有某种方式来实现目标??
【问题讨论】:
-
您需要将您的
return new Promise(function(resolve, reject) { ...放入$.getJSON('linkB', function(data) {...回调函数中。 -
小错误 Promise.all([A, B]).then(function() { console.log("Got A and B") });为此更改您的代码
-
@Krusader 不,OP 需要解决
getJSON函数中的承诺。 -
我还需要把它放在 getJson('linkA') 中吗?
-
@ÁlvaroTouzón:不,OP 正确调用
A和B。
标签: javascript html css json promise