I am chaining two calls to a function that uses fetch and returns a promise.
The calls sometimes arrive in the wrong order, reversed.
I assume my function code is wrong, derived from a bad understanding of either promises, fetch, or both.
This is the function code, simplified:
function shop(id) {
return new Promise(function(resolve, reject) {
fetch('/shop', {
method: 'post',
body: JSON.stringify({id: id}) ,
headers: {'Content-type': 'application/json '}
}).then(function (response) {
return response.json();
}).then(function (data) {
console.log(data);
resolve(data);
})
})
}
I chain the function in this manner:
shop('potatoe')
.then(shop('mushrooms'));
As explained, these two sometimes arrive in the wrong order, with mushrooms being shopped before potatoes.
May I have my returns or resolve() wrongly written in the shop() function?
Thank you for your help.