[英]Promise which inludes another async await promise - how to resolve?
我需要连续发出两个帖子请求。 有一个异步“post form”函数,它以“await”关键字开始请求,结果在“then”块中处理。
我尝试通过等待承诺来完成此发布请求,其中我调用了上面提到的异步函数。 问题是似乎无法在函数"then"
块内解决承诺。
我有一些示例代码来显示问题(查看start()
函数从哪里开始)。 见小提琴
//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();
我怎样才能解决第一个承诺,或者不可能? 还有其他解决方案吗? 这个想法是在第一个请求得到解决时发出另一个请求。
如果你使用的承诺,然后和你一起工作.then()
和.catch()
如果你有工作, async/ await
,那么你不使用.then()
和.catch()
因为异步/ AWAIT是语法糖,这样我们不需要一遍又一遍地嵌套我们的回答。
如果您想使用axios
或fetch
发出 2 个 post 请求,那么您可以简单地使用async / await
因为它们返回一个 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});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.