如果代码是这样的顺序写的(即把打印写在了接口里面)
_this.$api.systemAPI.chinacity().then((res) => {
res.data.map((v) => {
_this.allData.push({ name: v.city, value: v.num });
console.log(_this.allData);
});
console.log(_this.theTotal);
console.log("123");
console.log(_this.allData);
});
结果是
会按照顺序执行代码,先执行遍历里面的打印 等遍历完成后才继续执行后面的打印,符合js单线程的特性。
若把打印写在接口外面
_this.$api.systemAPI.chinacity().then((res) => {
res.data.map((v) => {
_this.allData.push({ name: v.city, value: v.num });
console.log(_this.allData);
});
});
console.log(_this.theTotal);
console.log("123");
console.log(_this.allData);
结果
代码先执行了接口外面的打印,没有按照顺序执行。 但这并不是说违背了js单线程的原理,实际上ajax是个异步操作,所以把执行的慢的代码挂起了,这也是异步操作的原理!!
如果在遍历之前加一行打印
_this.$api.systemAPI.chinacity().then((res) => {
console.log("接口掉通");
res.data.map((v) => {
_this.allData.push({ name: v.city, value: v.num });
console.log(_this.allData);
});
});
console.log(_this.theTotal);
console.log("123");
console.log(_this.allData);
结果
还是先执行了接口外面的打印,这说明没有按照顺序执行的原因是接口慢,不要误解为是遍历慢。