Javascript 代码执行先后顺序问题
hello 大家好,
我之前一直用 python 写一些小工具,最近开始用 JS 写东西,发现各种不适应:要么忘记放 ; , 要么数不清 { 和 } 是否成对。 这些都还好,多写一写也就习惯了,现在碰到一个代码执行顺序的逻辑问题:我有一个组订单号码,每个订单号码都要拿去进行 GET 请求,请求结果有一个变量要么 true 要么 false,我需要将根据这个变量将原始的订单号码分两组。
假设订单号码列表为:ordersID = [11, 12, 13, 21]
如果是 python,我可以这样写:
ordersID = [11, 12, 13, 21]; successful = list(); fail = list(); for x in ordersID: if (...): successful.append(x) else: fail.append(x) print(successful, fail) # [11,12, 13] [21]
为了精简我把条件部分省掉了
Javascript 我是这样写的:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>Testing!</h1> <script> var ordersID = ['11', '12', '13', '21']; var successful = []; var fail = []; function makeRequest(arg) { fetch(`https://jsonplaceholder.typicode.com/posts/${arg}`, {method: 'GET'}) .then(res => res.json()) .then(function (res) { if (res.userId == 2) { console.log(res); successful.push(arg); fetch('https://jsonplaceholder.typicode.com/posts', { method: 'POST', body: JSON.stringify({ title: 'Some title', body: arg, userId: 2 }), headers: { 'Content-type': 'application/json; charset=UTF-8' } }) .then(res => res.json()) .then(console.log) } else { console.log('userId != 2'); fail.push(arg) } }); }; for (i = 0; i < ordersID.length; i++) {makeRequest(ordersID[i]); console.log(successful, fail)}; </script> </body> </html>
我期望的结果是返回一个successful array 和一个 fail array,分别包含成功和失败的订单号码。可结果是返回空的 array 。我 JS 还没有好好学,只是边做边查,哪位盘友指点一下 🙂
想学习 你怎么粘贴代码的。。。。