猿问

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是没有值得,必须在里面加一个一次性定时器,延迟一下才可以,请问是为什么呢?

https://img4.mukewang.com/5ca2caf60001d4d108000376.jpg


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


          setTimeout(()=>{

                          console.log(_this.access_token);

                      },600)

https://img2.mukewang.com/5ca2caf900012f0e07360288.jpg


大话西游666
浏览 992回答 4
4回答

繁星coding

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

小唯快跑啊

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

Cats萌萌

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

幕布斯6054654

resolve()的执行位置有问题,请求没有响应就直接被resolve()到成功状态,resolve()写在响应为true的判断里
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答