(Axios顺序请求实战)一个Axios请求参数依赖于另一个Axios请求返回值


显示结果和说明

we are the world 是第一个firstRequest得到的返回值,将这个返回值赋值给hostName变量

之后secondRequest根据第一个请求所得到的返回值将返回值赋给第二个请求并得到返回的结果: res from second Request: res from first Request: we are the world

hostName: res from first Request: we are the world 
host2Name: res from second Request: res from first Request: we are the world

源码

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script src="https://cdn.staticfile.org/vue/2.4.2/vue.min.js"></script>
		<script src="https://cdn.staticfile.org/axios/0.18.0/axios.min.js"></script>
	</head>
	<body>
		<div id="app">
			hostName: {{hostName}}
			<br/>
			host2Name: {{host2Name}}
		</div>

		<script>
			var vm = new Vue({
				el: "#app",
				data() {
					return {
						hostName: null,
						host2Name: null,
					}
				},
				mounted() {
					this.sumRequest();
				},
				methods: {
					printInfo: function() {
						alert("printInfo method");
					},
					sumRequest: async function() {
						await this.firstRequest();
						await this.secondRequest();
					},
					firstRequest: function() {
						let _this = this;
						return new Promise((resolve, reject) => {

							// axios发送请求统一模板
							axios({
									method: 'get',
									url: 'http://httpbin.org/get',
									params: {
										param: "we are the world"
									}
								})
								.then(function(res) {
									// console.log("--->"res + JSON.stringify(res));
									_this.hostName = "res from first Request: " + res.data.args.param;
									resolve(res);
								}).catch(function(error) {
									console.log(error);
								});

						})
					},
					secondRequest: function() {
						let _this = this;
						console.log("host2Name: " + _this.host2Name);
						return new Promise((resolve, reject) => {
							// axios发送请求统一模板
							axios({
									method: 'get',
									url: 'http://httpbin.org/get',
									params: {
										param: "res from second Request: " + _this.hostName
									}
								})
								.then(function(res) {
									console.log("--->");
									console.log(JSON.stringify(res.data.args.param));
									_this.host2Name = res.data.args.param;
									resolve(res);
								}).catch(function(error) {
									console.log(error);
								});
						})

					},
				}
			});
		</script>
	</body>
</html>

原创文章,作者:jamestackk,如若转载,请注明出处:https://blog.ytso.com/275977.html

(0)
上一篇 2022年7月22日
下一篇 2022年7月22日

相关推荐

发表回复

登录后才能评论