Return object in a callback?

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