Return object in a callback?

Hi All,

I’m trying to wrap this function, which takes a URL and a callback. I tried the following:

structure = pv.io.fetchPdb("https://files.rcsb.org/view/5JQ3.pdb",function(x){return x;})

but I get undefined. Any ideas?

Currently broken notebook here:

https://beta.observablehq.com/@sdwfrost/protein-structure-viewing-with-pv

There’s a section in the Introduction to Promises notebook on adapting callback APIs to use Promises. Here, that might look like:

structure = new Promise(resolve => {
  pv.io.fetchPdb("https://files.rcsb.org/view/5JQ3.pdb", x => {
    resolve(x);
  });
})

Or, more succinctly:

structure = new Promise(resolve => pv.io.fetchPdb("https://files.rcsb.org/view/5JQ3.pdb", resolve))

Note that this code doesn’t handle errors, so if there’s a problem loading the file, it will wait forever. Most callback APIs pass an optional error as the first argument, but that doesn’t appear to be the case here. So you might do something like:

structure = new Promise((resolve, reject) => {
  pv.io.fetchPdb("https://files.rcsb.org/view/5JQ3.pdb", x => {
    if (x) resolve(x);
    else reject(new Error("load failed"));
  });
})
1 Like