如何使用javascript承诺ES6而不是jQuery ajax调用?

时间:2017-11-16 09:36:06

标签: javascript jquery ajax ecmascript-6

我试图了解承诺如何在javascript中运行,但我没有找到关于此的明确信息,我想知道是否可能而且它是如何使用promises而不是这个代码(等效)

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

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

我问这个因为我只想使用没有任何框架或插件的javascript,我对ES6的其他新功能没问题,我希望你能帮助我,谢谢。

2 个答案:

答案 0 :(得分:1)

你可以这样做

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

答案 1 :(得分:0)

你必须用实例化的函数包装你的ajax调用并返回一个promise:



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




然后你按照下面的承诺消费:

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