简体   繁体   English

如何更改 jQuery Ajax done 回调参数

[英]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使用 jQuery $.get 下载 json
  2. use the json to create an object使用 json 创建对象
  3. return the object返回对象


so that if I call所以如果我打电话

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

"a" would be the object created in step 2 “a”将是在步骤 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()"当我调用它时,我希望“.done()”部分会收到在“createObj()”中创建的“东西”
However, it turns out to be the json I've got in $.get()然而,结果是我在 $.get() 中得到的 json

Did I misunderstand the concept of "Resolve"?我是否误解了“解决”的概念?
Or is jQuery Ajax behave different from standard ES6 Promise?还是 jQuery Ajax 的行为与标准 ES6 Promise 不同? Because I wrote something with Promise.resolve in other part, and it worked因为我在其他部分用 Promise.resolve 写了一些东西,它奏效了

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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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