vue中遇到的小问题,this.XXX不能直接拿到需要等待一下才能拿到是为什么啊?

vue中遇到的小问题,this.XXX不能直接拿到需要等待一会才能拿到是为什么啊?

我现在是在调用两个接口,比如是A和B,
等A结束之后我才可以调用B接口,(因为A接口返回数据我拿到B接口要用到)

我代码是这样的

                        let promise = new Promise(function(resolve, reject) {
            //获取Access Token
                          axios.get("api/token?grant_type=client_credential&appid=appid&secret=secret")
                                        .then(function(response) {
                                            _this.access_token=response.data.access_token;
                                            console.log(_this.access_token);
                                        })
                                        .catch(function(error) {
                                            // error
                                            console.log(error);
                                        });
                            resolve();
                        });
                    promise.then(function() {
                      //获取jsapi_ticket
                      console.log(_this.access_token);
                       axios.get("api/ticket/getticket?access_token="+_this.access_token+"&type=jsapi")
                                        .then(function(response) {
                                            //数据    success
                                            console.log(response);
                                        })
                                        .catch(function(error) {
                                            // error
                                            console.log(error);
                                        });

                    });
                    

A接口完成之后抛出resolve B接口访问,但是我的_this.access_token是没有值得,必须在里面加一个一次性定时器,延迟一下才可以,请问是为什么呢?

clipboard.png

clipboard.png

是空的,加个延迟就可以了,为什么呢?

          setTimeout(()=>{
                          console.log(_this.access_token);
                      },600)

clipboard.png

阅读 2.7k
4 个回答

通过resolve(response.data.access_token)向下传递就可以了

新手上路,请多包涵

你好,试试axios.get().then(function(response){
resolve(); //这个放在请求完成的函数中调用
})

new promise改成箭头函数,分分钟可以

resolve()的执行位置有问题,请求没有响应就直接被resolve()到成功状态,resolve()写在响应为true的判断里

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题