【发布时间】:2016-06-07 10:27:57
【问题描述】:
我有 2 个 csv 正在尝试读取,之后我使用这两个中的数据来做事:
function getData() {
var deferredObject = $.Deferred(); //representation of some asynchronous work
d3.csv("./parse_shp.csv", function(data) {
console.log(data);
shp_array = data;
});
d3.csv("./fao_coutnry_shp.csv", function(data) {
console.log(data);
fao_array = data;
});
//once both of those are done, resolve the promise
deferredObject.resolve();
return deferredObject.promise();
}
function LevenshteinDistance() {
console.log("do stuff with the data");
}
//call LevenDistance after the promise has been resolved
getData().then(LevensteinDistance());
但这不起作用......它会在打印 csv 的数据之前打印"do something with the data" 行。
我做错了什么?我以this 链接为例。
我不明白如何连接deferredObject 和getData()?因为即使我在函数中创建了延迟对象,它不会只是异步读取 csv 然后错误地调用defferedObject.resolve() 吗?
无论如何,我是新的承诺,所以任何帮助将不胜感激!
【问题讨论】:
-
您在任一 .csv 方法完成之前解决了承诺。
-
@KevinB 谢谢!那么他们完成后我将如何解决它?我是否必须将承诺绑定到 csv 方法本身?
-
getData().then(LevensteinDistance());是一个错误,你不应该 CALL LevensteinDistance 并将其返回值传递给then,你应该只传递LevensteinDistance(函数)而不是() -
@PJSCopeland 您应该在对问题代码进行重大更改之前与 OP 进行验证。
标签: javascript jquery asynchronous promise