异步ajax如何获取返回值?

异步ajax设置返回值因为是异步 所以没获取到值就会返回
接收到的往往是undefined
那么把异步改成同步以外
有没有什么方法可以获取异步的ajax
我本来的思路是接受函数给个async 然后调用语句加awiat
但是获取的是promise之类的东西
并没有获取到数据
异步怎样获取返回值呢?
在不使用框架的情况下 原生js有没有办法解决?

阅读 5.9k
2 个回答

闭包

function a1(data){
    console.log(data)
}
$.ajax().done(function(data){
    a1(data)
})

可以用es6的Generator改造promise为同步 co.js就是这样做的 co简写:

function co(generator) {
  return function(fn) {
    var gen = generator();
    function next(err, result) {
        if(err){
            return fn(err);
        }
        var step = gen.next(result);
        if (!step.done) {
            step.value(next);
        } else {
            fn(null, step.value);
        }
    }
    next();
   }
}
co(function * () {
    var data= yield $.ajax('a.json');
    //同步写法
    console.log(data);
})

Axios 是一个基于 promise 的 HTTP 库,可以看看 : https://github.com/axios/axios

例子:

// Make a request for a user with a given ID
axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

// Make a postrequest
axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题