created生命周期中第二个请求依赖于第一个请求返回的结果

        uniapp中向后端发出请求时,第二个请求里的参数是第一个请求中返回的结果,但第二个请求返回数据错误。

		created() {
			// 在组件创建时获取查询参数
			this.pinpai = this.$route.query.name;
			http({
			  url: '/get_rating',
			  method: 'GET',
			  data: {
			    productName: this.pinpai,
			  }
			}).then((res) => {
				console.log(res);
				this.productId = res.data.productId;
				this.score = res.data.rating/2;
			});
			http({
				url: '/show_word_cloud',
				method: 'GET',
				data:{
					productId: this.productId,
				}
			}).then((res)=>{
				console.log(res);
				console.log(this.productId);
				this.wordList = res.data.list;
				console.log(this.wordList);
			});
		},

        问题出在两个HTTP请求是异步执行的,这意味着第二个请求不会等待第一个请求完成就会发送,因此this.productId可能还没有被设置就已经被使用了。

        所以需要确保第二个请求在第一个请求成功后再发送。可以在第一个请求的回调函数中触发第二个请求(将第二个请求封装为一个函数放在methods里,在第一个请求的最后调用),或者使用Promise链来确保它们按顺序执行:

created() {
  // 在组件创建时获取查询参数
  this.pinpai = this.$route.query.name;
  http({
    url: '/get_rating',
    method: 'GET',
    data: {
      productName: this.pinpai,
    }
  }).then((res) => {
    console.log(res);
    this.productId = res.data.productId;
    this.score = res.data.rating / 2;

    // 在第一个请求成功后,触发第二个请求
    return http({
      url: '/show_word_cloud',
      method: 'GET',
      data: {
        productId: this.productId,
      }
    });
  }).then((res) => {
    console.log(res);
    console.log(this.productId);
    this.wordList = res.data.list;
    console.log(this.wordList);
  }).catch((error) => {
    console.error('Error:', error);
  });
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值