最近有一个点一个按钮调用多个接口,并且按顺序串行调用,根据后端返回的逻辑,区分接口之间的串行关系,前面的接口失败是否继续执行下面接口,有两种方式,都是循环调用接口,实现方式有点差别
第一种reduce+promise
var resolves = [];
callAPI(obj) { return new Promise((resolve, reject) => { let params = { channelCode: "SW01", menuCode: "10302", operatorNo: this.operatorNo, }; obj["apiName"](Object.assign(params, obj.parse)) .then((res) => { if (Object.keys(res).length > 0) { resolves.push(res); } resolve(res); }) .catch((err) => { if (Object.keys(err).length > 0) { resolves.push(err); }
// 如果不需要管前面接口返回结果,这里写resolve(err),否则写reject(err) resolve(err); }); }); }, async dealFuc() { const arr = [ { apiName: corpCheckCustomer, parse: { transCode: "TNEC2003", customerNo: "303390266", }, }, { apiName: accSonTypeQuery, parse: { transCode: "TNYK0009", productCode: "11020004", }, }, ]; return arr.reduce((chain, url) => { return chain.then(() => { return this.callAPI(url); }); }, Promise.resolve()); }, // 初始化调用,放在mounted中 this.dealFuc() .then((res) => { modal.alert({ message: JSON.stringify(resolves, null, 2), okTitle: "接收到的值", }); this.log("所有接口调用完成", "success"); }) .catch((err) => { modal.alert({ message: err, okTitle: "报错" }); this.log("执行过程中出错", "error"); });
第二种方法:for循环+promise
function dealFuc() { const arr = [ { apiName: corpCheckCustomer, parse: { transCode: "", customerNo: "303390266", }, }, { apiName: accSonTypeQuery, parse: { transCode: "TNYK0009", productCode: "11020004", }, }, ]; (async () => { try { var data = []; for (var i = 0; i < arr.length; i++) { let result = await new Promise((resolve, reject) => { setTimeout(() => { let params = { channelCode: "SW01", menuCode: "10302", operatorNo: this.operatorNo, }; arr[i]["apiName"](Object.assign(params, arr[i].parse)) .then((res) => { resolve(res); }) .catch((err) => { // 判断如果第二个接口依赖于第一个接口,则写成reject(err),否则resolve(err) resolve(err); }); }); }); if (Object.keys(result).length > 0) { data.push(result); } } this.$logi("data:======", data); } catch (e) { console.log({ message: e }); } })(); }
标签:arr,resolve,apiName,err,res,顺序调用,接口,vue2 From: https://www.cnblogs.com/florazeng/p/18150568