export const wxreq = (config) => {
config.url = `${HTTP_HOST}${config.url}`;
return new Promise((resolve, reject) => {
return wepy.request(Object.assign(config, {
async success (res) {
// res is a promise, this promise is return {data: 123}
const responseFromMiddle = await res;
return resolve(responseFromMiddle.data);
},
fail () {
reject(new Error(`Request ${config.url} fail!`));
},
complete () {
resolve();
}
}))
})
};
在vuejs生命周期中
async onReady () {
cosnt res = wxreq(someCorrectConfig);
console.log(res); // undefined; need to be 123
}
我很好奇为什么没有定义res?请帮忙〜这么困惑!thx~
答案 0 :(得分:0)
实施似乎有问题。 要调用wxreq,您需要在此之前使用await。同时将该条件包装在try块中以捕获ant异常。
async onReady () {
try {
const res = await wxreq(someCorrectConfig);
console.log(res); // undefined; need to be 123
}
catch(err){
console.log(err)
}
}
答案 1 :(得分:0)
试试这个:在await
函数
async
async onReady () {
const res = await wxreq(someCorrectConfig);
console.log(res); // undefined; need to be 123
}
并删除承诺中的return
export const wxreq = (config) => {
config.url = `${HTTP_HOST}${config.url}`;
return new Promise((resolve, reject) => {
wepy.request(Object.assign(config, {
async success (res) {
// res is a promise, this promise is return {data: 123}
const responseFromMiddle = await res;
return resolve(responseFromMiddle.data);
},
fail () {
reject(new Error(`Request ${config.url} fail!`));
},
complete () {
resolve();
}
}))
})
};
答案 2 :(得分:0)
我认为你应该这样做
export async function wxreq(config) {
const res = await new Promise((resolve, reject) => {
wepy.request(Object.assign(config, {
url: `${HTTP_HOST}${config.url}`,
success: resolve,
fail: reject
});
});
return res.data;
}
但很难说不知道wepy
是什么。