score:1

Accepted answer

Although there are many twists and turns when it comes to using Promises, it turns out that the actual changes required to port code to make use of the d3-fetch module in favor of the deprecated d3-request module are strikingly minimal. Loosely speaking, to adapt your—or any pre-v5—code to use the new d3-fetch module you just move the callback from one method to another. Thus, the former

d3.dsv(url, callback);

now becomes

d3.dsv(url).then(callback);

The only thing to be aware of is to check if the callback's signature matches the one expected for .then. This only becomes relevant, though, if your callback used two parameters to handle errors:

function callback(error, data) {
  // Handle error
  if (error) throw error;

  // Manipulate data
}

With Promises this is split into two separated methods:

function onFullfilled(data) {
  // Manipulate data
}

function onRejected(error) {
  // Handle error
}

These callback can be used in two ways:

// 1.
d3.dsv(url).then(onFullfilled, onRejected);

// 2.
d3.dsv(url).then(onFullfilled).catch(onRejected);

Another important point is that you cannot return data from your callback (beware of the infamous "How do I return the response from an asynchronous call?"!). d3.dsv now returns a Promise, not your data; you have to handle the data inside your callback. If you become more skilled using Promises you might have a look into the await operator, though, which allows you to wait for a Promise and its fulfilled value. Although this is ECMAScript 2017 (ES8) syntax it has already seen wide-spread browser support.


That being the general case, now for your code: sampleData is an Array object which, of course, does not have a .then() method and, hence, the error. To make the code work there is not much to do apart from uncommenting the lines featuring d3.dsv and putting the relevant code handling data inside the callback.

If you really want to do an offline simulation with hardcoded data you can use Promise.resolve() which will return a Promise already resolved with the given value. In your case instead of

d3.csv("my-data.csv")
  .then(function(data) { });

you can use

Promise.resolve(sampleDate)
  .then(function(data) { });   // Same handler as above

Related Query

More Query from same tag