Vue中js 后边的代码比前边的先执行
最近在项目中遇到了一个比较怪的js问题,
写在后边的代码先于前边的执行,
先看下出问题的代码:
beforeUploadFunc(file) {
let size = file.size / 1024 / 1024;
if (size > 1) {
this.$message.warning('不超过500kb')
return;
}
getStsToken().then(response => { // 同步等待ossConf初始化
const stsCredentials = response.data.data;
this.ossConf.securityToken = stsCredentials.securityToken;
this.ossConf.accessKeyId = stsCredentials.accessKeyId;
this.ossConf.accessKeySecret = stsCredentials.accessKeySecret;
this.ossConf.expiration = stsCredentials.expiration;
this.ossConf.region = 'oss-cn-hangzhou';
this.ossConf.bucket = 'img-x';
console.log(1);
}).catch((err) => {
console.log('getStsToken 异常', err);
this.$message.error('上传出错,请刷新后重试');
});
console.log(2);
let ossClient = new OSS({
region: this.ossConf.region,
stsToken: this.ossConf.securityToken,
accessKeyId: this.ossConf.accessKeyId,
accessKeySecret: this.ossConf.accessKeySecret,
bucket: this.ossConf.bucket
});
}
就是这段代码,当我在let ossClient的时候,报错缺少accessKeyId,
可是this.ossConf.accessKeyId这个变量是在前边的代码中赋值过的,
后来通过console.log观察,2在1之前打印出来,
也就是调用getStsToken()后then的这段代码是比后边的晚执行,
这里是getStsToken的代码:
export function getStsToken() {
return request({
url: '/member/oss/getToken',
method: 'get'
})
}
就觉得是不是异步请求的原因。
我们项目中用到的是axios,axios是异步请求,
这里我们需要同步调用getStsToken,使用await等待异步请求执行完成。
修改getStsToken()方法,添加关键字async:
export async function getStsToken() {
return request({
url: '/member/oss/getToken',
method: 'get'
})
}
修改调用的地方,beforeUploadFunc方法:
在beforeUploadFunc方法前加async关键字;
在调用getStsToken,方法前加await关键字。
async beforeUploadFunc(file) {
let size = file.size / 1024 / 1024;
if (size > 1) {
this.$message.warning('不超过500kb')
return;
}
await getStsToken().then(response => { // 同步等待ossConf初始化
const stsCredentials = response.data.data;
this.ossConf.securityToken = stsCredentials.securityToken;
this.ossConf.accessKeyId = stsCredentials.accessKeyId;
this.ossConf.accessKeySecret = stsCredentials.accessKeySecret;
this.ossConf.expiration = stsCredentials.expiration;
this.ossConf.region = 'oss-cn-hangzhou';
this.ossConf.bucket = 'img-pay';
}).catch((err) => {
console.log('getStsToken 异常', err);
this.$message.error('上传出错,请刷新后重试');
});
let ossClient = new OSS({
region: this.ossConf.region,
stsToken: this.ossConf.securityToken,
accessKeyId: this.ossConf.accessKeyId,
accessKeySecret: this.ossConf.accessKeySecret,
bucket: this.ossConf.bucket
});
}
问题解决。
参考资料: