# Return object in a callback?

**URL:** <https://talk.observablehq.com/t/return-object-in-a-callback/292>\
**Category:** Uncategorized\
**Created:** [February 11, 2018, 4:27pm UTC](https://talk.observablehq.com/t/return-object-in-a-callback/292 "2018-02-11T16:27:56Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![sdwfrost](https://yyz2.discourse-cdn.com/flex030/user_avatar/talk.observablehq.com/sdwfrost/32/139_2.png) [@sdwfrost](https://talk.observablehq.com/u/sdwfrost)\
**Post date:** [February 11, 2018, 4:27pm UTC](https://talk.observablehq.com/t/return-object-in-a-callback/292/1 "2018-02-11T16:27:56Z")

</div>

Hi All,

I’m trying to wrap [this function](http://pv.readthedocs.io/en/v1.8.1/mol.html?highlight=fetchPdb#pv.io.fetchPdb), which takes a URL and a callback. I tried the following:

```auto
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](https://beta.observablehq.com/@sdwfrost/protein-structure-viewing-with-pv)

---

<div class="post-metadata">

**Author:** ![mbostock](https://yyz2.discourse-cdn.com/flex030/user_avatar/talk.observablehq.com/mbostock/32/9_2.png) [@mbostock](https://talk.observablehq.com/u/mbostock)\
**Post date:** [February 11, 2018, 11:20pm UTC](https://talk.observablehq.com/t/return-object-in-a-callback/292/2 "2018-02-11T23:20:32Z")

</div>

There’s a section in the [Introduction to Promises](https://beta.observablehq.com/@mbostock/introduction-to-promises) notebook on adapting callback APIs to use Promises. Here, that might look like:

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

```

Or, more succinctly:

```auto
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:

```auto
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"));
  });
})

```
