简体   繁体   English

如何使用JavaScript Promise ES6代替jQuery ajax调用?

[英]How to use javascript promises ES6 instead of jQuery ajax call?

I was trying to understand how promises works in javascript but I didn't found clear info about this, I would like to know if it possible and it is so how to do this using promises instead this code (equivalent) 我试图了解Promise如何在javascript中工作,但我没有找到明确的信息,我想知道是否有可能,因此如何使用Promise代替此代码(等效)

$.ajax({
    type: 'post',
    cache: false,
    url: 'myfile.php',
    data: { info: info },
    datatype: 'json',

    success: function(response) {
        console.log(response);
    }
});

I ask this because I want to use only javascript without any framework or plugins, I have no problem with the other new feautures of ES6 just with this one, I hope you can help me, thanks. 我之所以这样问是因为我只想使用没有任何框架或插件的javascript,就此而言,我对ES6的其他新功能没有任何疑问,希望您能对我有所帮助,谢谢。

You have to wrap your ajax call with a function that instantiates and returns a promise: 您必须使用实例化并返回Promise的函数包装ajax调用:

 function getSomething() { return new Promise((resolve, reject) => { $.ajax({ type: 'post', cache: false, url: 'myfile.php', data: { info: info }, datatype: 'json', success: function(response) { resolve(response); }, error: function() { reject("some errors"); } }); }); } 

Then you consume your promise like below: 然后,您将如下兑现承诺:

getSomething()
    .then(response => console.log(response))
    .catch(err => console.log(err));

You could do it like this 你可以这样

function doAjax() {
   return $.ajax({
        type: 'post',
        cache: false,
        url: 'myfile.php',
        data: { info: info },
        datatype: 'json',
    });
}
doAjax.then(function(data) {
    // do success stuff
}).fail(function() {
    // do fail stuff
});

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

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