简体   繁体   English

Ember.RSVP.Promise中的AJAX调用

[英]AJAX call inside Ember.RSVP.Promise

I have the following common code to invoke AJAX requests. 我有以下通用代码来调用AJAX请求。 My question is if the "return" keyword is necessary for the $.ajax (since doing $.ajax would anyways return a promise) OR if it is for some other purpose ? 我的问题是$ .ajax是否必须使用“ return”关键字(因为执行$ .ajax无论如何都会返回一个Promise)还是出于其他目的?

doXhr: function(postData, requestUrl){  
    var promise = new Ember.RSVP.Promise(function(resolve, reject) {        
        return $.ajax({ //Is the "return" required on this line ?
            url: requestUrl,

        })
        .done(function(response, status, xhrObject) {         
          resolve(response);
        })
        .fail(function(xhrObject, status, error){           
            reject(errorObj);
        });
    })  
    return promise;
},

just like other promise libraries (Native, Bluebird, etc), the resolve , reject functions are actually callbacks, so there is no need for a return inside the new Promise . 就像其他promise库(Native,Bluebird等)一样, resolvereject函数实际上是回调,因此不需要在new Promise返回。 (If you never call resolve or reject though, your promise will be pending forever). (但是,如果您从未致电解决或拒绝,您的承诺将永远待定)。

The only return that is needed in the return of the RSVP.Promise like what you have at the bottom -- though only if you are await ing or then ing doXhr RSVP.Promise的返回中唯一需要的返回,就像您在底部RSVP.Promise那样-尽管只有在awaitthen doXhr

Also, neat side-tip: 另外,简洁的提示:

With the the more recent ember, you can just do: 使用最新的余烬,您可以这样做:

import { Promise } from 'rsvp';

new Promise((resolve, reject) => {
  // stuff
});

Edit 编辑

for how the function body of the promise get's executed, you'll need to look at the constructor of the Promise: https://github.com/tildeio/rsvp.js/blob/master/lib/rsvp/promise.js#L143 有关如何执行promise的函数体,您需要查看Promise的构造函数: https : //github.com/tildeio/rsvp.js/blob/master/lib/rsvp/promise.js# L143

the resolver function (the function you define when making a new promise) is passed to here https://github.com/tildeio/rsvp.js/blob/master/lib/rsvp/-internal.js#L231 and then evaluated. resolver功能(做出新承诺时定义的功能)将传递到此处https://github.com/tildeio/rsvp.js/blob/master/lib/rsvp/-internal.js#L231 ,然后进行评估。

Hope this helps! 希望这可以帮助!

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

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