I am making several asynchronous ajax calls which must be executed in a specific order and which must pass information to each other. Here is a MWE of my current approach. Even with three API calls it is a bit of a nightmare. With 5 it’s impossible to line up the error workflow or to move functions around (also I run out of screen space). Is there a better approach to achieve this same outcome?
JavaScript
x
61
61
1
/*
2
* API Call to get user
3
*/
4
$.ajax({
5
type: 'POST',
6
url: `robin.hood/get_user`,
7
data: JSON.stringify({"name":"Joe Dirt"}),
8
headers: {Authorization: 'Bearer ' + token},
9
datatype: 'json',
10
contentType: 'application/json; charset=utf-8',
11
success: function (data, text_status, jq_xhr) {
12
/*
13
* Assume one user is returned only
14
*/
15
let user_id = data;
16
17
/*
18
* API Call to get the bank balance of the user
19
*/
20
$.ajax({
21
type: 'POST',
22
url: `robin.hood/get_user_balance`,
23
data: JSON.stringify({"user_id":user_id}),
24
headers: {Authorization: 'Bearer ' + token},
25
datatype: 'json',
26
contentType: 'application/json; charset=utf-8',
27
success: function (data, text_status, jq_xhr) {
28
/*
29
* We record the balance
30
*/
31
let balance = data;
32
33
/*
34
* We invest in Gamestop stock
35
*/
36
$.ajax({
37
type: 'POST',
38
url: `robin.hood/buy_gamestop_stock`,
39
data: JSON.stringify({"user_id":user_id, "amount":balance}),
40
headers: {Authorization: 'Bearer ' + token},
41
datatype: 'json',
42
contentType: 'application/json; charset=utf-8',
43
success: function (data, text_status, jq_xhr) {
44
/* STONKS!!! */
45
});
46
},
47
error: function (jq_xhr, text_status, error_thrown) {
48
/* NO STONKS */
49
}
50
});
51
},
52
error: function (jq_xhr, text_status, error_thrown) {
53
/* NO STONKS */
54
}
55
});
56
},
57
error: function (jq_xhr, text_status, error_thrown) {
58
/* NO STONKS */
59
}
60
});
61
Related but not so clear questions:
- Chaining multiple jQuery ajax requests
- jquery how to use multiple ajax calls one after the end of the other
Advertisement
Answer
$.ajax
returns a Thenable, which means you can await
it inside an async
function, which is easier to manage than nested callbacks:
JavaScript
1
29
29
1
async function run() {
2
try {
3
const user = await $.ajax({
4
type: 'POST',
5
url: `robin.hood/get_user`,
6
data: JSON.stringify({
7
"name": "Joe Dirt"
8
}),
9
headers: {
10
Authorization: 'Bearer ' + token
11
},
12
datatype: 'json',
13
contentType: 'application/json; charset=utf-8',
14
})
15
16
const balance = await $.ajax({
17
// ...
18
})
19
20
const data = await $.ajax({
21
// ...
22
})
23
24
/* STONKS!!! */
25
} catch (e) {
26
/* NO STONKS */
27
}
28
}
29
run()