简体   繁体   中英

How to change jQuery Ajax done callback param

I want the function to do these things, and to be an async function:

  1. download json with jQuery $.get
  2. use the json to create an object
  3. return the object


so that if I call

func.then(a => {
  ...
})

"a" would be the object created in step 2

So I have written,

    createObj(sourceUrl) {
        return $.get(sourceUrl).done((data)=> {
            let thing = new Something();
            thing.id = data.id;
            thing.messages = data.messages; 

            return Promise.resolve(thing);
        })
    }

and I call it

this.createObj(url).done((thing) => {
  console.log('Got a', thing);
  return thing.go()
}

When I call it, I expect the ".done()" part will receive "thing" created in "createObj()"
However, it turns out to be the json I've got in $.get()

Did I misunderstand the concept of "Resolve"?
Or is jQuery Ajax behave different from standard ES6 Promise? Because I wrote something with Promise.resolve in other part, and it worked

This should work:

const createObj = (sourceUrl) => {
  return new Promise((resolve, reject) => {
    $.get(sourceUrl).done((data)=> {
      let thing = new Something();
      thing.id = data.id;
      thing.messages = data.messages; 

      return resolve(thing);
    });
  });
}

createObj(url)
  .then((data) => console.log(data));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM