jQuery承诺不起作用?

时间:2016-02-24 21:51:32

标签: javascript jquery asynchronous promise

我有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链接为例。

我不明白联系deferredObjectgetData()的方式?因为即使我在函数中创建了延迟对象,也只是异步地执行csv读取然后错误地调用defferedObject.resolve()

无论如何,我是新的承诺,所以任何帮助都将不胜感激!

1 个答案:

答案 0 :(得分:2)

.then()的参数必须是函数。您立即调用函数,因为函数名后面有()。它应该是:

getData().then(LevenshteinDistance);