在for循环中,我想更改每个成功响应中的voucher的值。然后将更改后的值用于下一个增量循环执行。
服务器端程序
exports.vouchers = functions.https.onRequest((req, res) => {
cors(req, res, () => {
let amount = req.query.Amount;
let coupon_code = req.query.CouponCode;
let voucherAmount = req.query.voucher;
let user_id = req.query.user_id;
if (coupon_code === "VOUCHER"){
if(voucherAmount>=25){
if (!amount) {
amount = req.body.Amount;
}
let discount;
if (amount >= 350){
discount = "25";
} else{
discount = "SOMETHING WRONG";
}
res.status(200).send(discount);
} else {
res.status(200).send("INVALID");
}
}
else{
res.status(200).send("INVALID");
}
});
});
客户端程序
private void calcCoupon() {
String VOUCHER = "VOUCHER";
discount=0f;
String amount,voucher="35";
for(int i=0;i<cart.size();i++){
amount = cart.get(i).getPrice().toString();
OkHttpClient httpClient = new OkHttpClient();
HttpUrl.Builder httpBuider =
HttpUrl.parse(VOUCHER_URL).newBuilder();
httpBuider.addQueryParameter("CouponCode", VOUCHER);
httpBuider.addQueryParameter("Amount", amount);
httpBuider.addQueryParameter("voucher",voucher);
Request request = new Request.Builder().
url(httpBuider.build()).build();
final int finalI = i;
httpClient.newCall(request).enqueue(new Callback() {
@Override public void onResponse(Call call, Response response){
ResponseBody responseBody = response.body();
{
resp = responseBody.string();
switch (resp) {
case "INVALID":
Log.d("FOR_LOOP_RESPONSE","INVALID COUPON CODE"+ " For Parameter "+ finalI);
break;
case "SOMETHING WRONG":
Log.d("FOR_LOOP_RESPONSE","SOMETHING WRONG"+ " For Parameter "+ finalI);
break;
case "":
Log.d("FOR_LOOP_RESPONSE","...");
break;
default:
discount = Float.valueOf(resp);
//HERE UPDATE VOUCHER VALUE
voucher = String.valueOf(Float.valueOf(voucher)-discount);
Log.d("FOR_LOOP_RESPONSE", discount + " For Parameter "+ finalI +". VOUCHER"+voucher);
break;
}
}
}
}
);
}
}
我想要这样的结果
FOR_LOOP_RESPONSE:某些错误,参数0 FOR_LOOP_RESPONSE:25.0对于参数1. VOUCHER 10.0 FOR_LOOP_RESPONSE:对于参数2无效
但是实际结果是这样的,
FOR_LOOP_RESPONSE:25.0对于参数1。VOUCHER10.0 FOR_LOOP_RESPONSE:参数0的某些错误FOR_LOOP_RESPONSE: 25.0对于参数2。VOUCHER-15.0