Reputation: 5328
I need to make two post requests in succession. There is an async "post form" function which starts the request with the "await" keyword and the result is handled in the "then" block.
I try to do this post request by awaiting a promise, wherein I call the above mentioned async function. The problem is that it doesn't seem that the promise can be resolved inside the functions "then"
block.
I have some example code to show the issue (look at start()
function where it starts). See fiddle
//Returns a promise. It contains another async-await promise
function mainFunction() {
return new Promise( () => { //<-- this never resolves
async function postForm(){
//(Post a form)
await new Promise( (resolve, reject) => {
setTimeout(() => {
resolve('resolved');
}, 2000);
}).then( response => { // <-- how to resolve the first promise inside here?
console.log('promise 2 response: ',response)
//Try to resolve the 1st promise (doesn't work)
new Promise( (resolve,reject) => resolve('promise 1 resolved') );
}).catch( error => {
console.log(error)
})
}
postForm();
})
}
//Make two posts in succession
async function start(){
//Post 1 - (never resolves)
await mainFunction().then( response => {
//(Next: make post request 2)
}).catch( error => {
console.log(error)
})
}
start();
How can I resolve the first promise, or isn't it possible? Is there some other solution? The idea is to make another post request when the first one is resolved.
Upvotes: 2
Views: 284
Reputation: 14904
If you use promises then you work with .then()
and .catch()
if you work with async/ await
then you dont use .then()
and .catch()
because async / await is syntatic sugar so that we dont need to nest our responses over and over.
If you want to make 2 post request for example with axios
or fetch
then you can simply use async / await
because they return an promise.
async function requests(){
//await makes the request wait till it gets some response
const response1 = await axios.post("url", {data});
const response2 = await axios.post("url2", {data});
}
Upvotes: 1