遵义创意网站设计,商品推广软文范例300字,天津西青网站建设公司,网站优化查询一、异步的方法#xff0c;如果不传入 success、fail、complete 等 callback 参数#xff0c;将以 Promise 返回数据异步的方法#xff0c;且有返回对象#xff0c;如果希望获取返回对象#xff0c;必须至少传入一项 success、fail、complete 等 callback 参数#xff0c…一、异步的方法如果不传入 success、fail、complete 等 callback 参数将以 Promise 返回数据异步的方法且有返回对象如果希望获取返回对象必须至少传入一项 success、fail、complete 等 callback 参数列如 // 正常使用const task uni.connectSocket({success(res){console.log(res)}})// Promise 化uni.connectSocket().then(res {// 此处即为正常使用时 success 回调的 res// uni.connectSocket() 正常使用时是会返回 task 对象的如果想获取 task 则不要使用 Promise 化console.log(res)})二、Vue 2 和 Vue 3 的 API Promise 化
PS
Vue2 对部分 API 进行了 Promise 封装返回数据的第一个参数是错误对象第二个参数是返回数据。此时使用 catch 是拿不到报错信息的因为内部对错误进行了拦截。Vue3 对部分 API 进行了 Promise 封装调用成功会进入 then 方法 回调。调用失败会进入 catch 方法 回调
Vue2
// 默认方式
uni.request({url: https://www.example.com/request,success: (res) {console.log(res.data);},fail: (err) {console.error(err);},
});// Promise
uni.request({url: https://www.example.com/request,}).then((data) {// data为一个数组// 数组第一项为错误信息 即为 fail 回调// 第二项为返回数据var [err, res] data;console.log(res.data);});// Await
async function request() {var [err, res] await uni.request({url: https://www.example.com/request,});console.log(res.data);
}Vue3:
// 默认方式
uni.request({url: https://www.example.com/request,success: (res) {console.log(res.data);},fail: (err) {console.error(err);},
});// 使用 Promise then/catch 方式调用
uni.request({url: https://www.example.com/request,}).then((res) {// 此处的 res 参数与使用默认方式调用时 success 回调中的 res 参数一致console.log(res.data);}).catch((err) {// 此处的 err 参数与使用默认方式调用时 fail 回调中的 err 参数一致console.error(err);});// 使用 Async/Await 方式调用
async function request() {try {var res await uni.request({url: https://www.example.com/request,});// 此处的 res 参数与使用默认方式调用时 success 回调中的 res 参数一致console.log(res);} catch (err) {// 此处的 err 参数与使用默认方式调用时 fail 回调中的 err 参数一致console.error(err);}
}返回格式互相转换
Vue2
// Vue 2 转 Vue 3, 在 main.js 中写入以下代码即可
function isPromise(obj) {return (!!obj (typeof obj object || typeof obj function) typeof obj.then function);
}uni.addInterceptor({returnValue(res) {if (!isPromise(res)) {return res;}return new Promise((resolve, reject) {res.then((res) {if (!res) {resolve(res);return;}if (res[0]) {reject(res[0]);} else {resolve(res[1]);}});});},
});Vue3:
// Vue 3 转 Vue 2, 在 main.js 中写入以下代码即可
function isPromise(obj) {return (!!obj (typeof obj object || typeof obj function) typeof obj.then function);
}uni.addInterceptor({returnValue(res) {if (!isPromise(res)) {return res;}const returnValue [undefined, undefined];return res.then((res) {returnValue[1] res;}).catch((err) {returnValue[0] err;}).then(() returnValue);},
});