如何获取在 vue页面如何获取resolve 这个变量
Function.js页面代码
const BASE_URL = `http://localhost/app/`
export const myRequest = (options) => { //暴露一个function:myRequest,使用options接收页面传过来的参数
return new Promise((resolve)=>{
uni.request({
url: BASE_URL + options.url,
data: options.data || {}, //接收请求的data,不传默认为空
method: options.method || 'GET', //接收请求的方式,如果不传默认为GET
header: {
'content-type': 'application/x-www-form-urlencoded',
},
success: (res) => {
//console.log(res) // 将请求结果resolve出去
resolve(res) // 将请求结果resolve出去
}
})
})
}
vue页面代码:
//封装函数开始myRequest
getData2() {
//开始请求服务器数据结束
this.myRequest({
url: '1.asp',
data: {
id1: 2,
id2: 'addoil',
},
method: '',
})
console.log(resolve)//无法获取这个resolve变量
//开始请求服务器数据结束
},
//封装函数结束
// 第一种
async getData2() {
//开始请求服务器数据结束
const res = await this.myRequest({
url: '1.asp',
data: {
id1: 2,
id2: 'addoil',
},
method: '',
})
console.log(res )
// 第二种
getData2() {
//开始请求服务器数据结束
this.myRequest({
url: '1.asp',
data: {
id1: 2,
id2: 'addoil',
},
method: '',
}).then(res => {
console.log(res )
})
该回答引用ChatGPT
在Vue页面中无法直接获取resolve变量,因为它是一个函数内部的局部变量。通常情况下,您应该在使用myRequest函数的地方处理resolve返回的结果,而不是在函数外部访问它。例如,在您的Vue页面代码中,您可以通过将myRequest函数返回的Promise对象保存到一个变量中来处理resolve返回的结果:
getData2() {
this.myRequest({
url: '1.asp',
data: {
id1: 2,
id2: 'addoil',
},
method: '',
}).then(res => {
// 处理返回的结果
console.log(res)
}).catch(err => {
// 处理请求失败的情况
console.log(err)
})
},
在这个例子中,then方法用于处理resolve返回的结果,而catch方法用于处理请求失败的情况。您可以在then和catch方法中执行任何需要执行的代码来处理结果和错误。
不知道你这个问题是否已经解决, 如果还没有解决的话: