【发布时间】:2020-07-04 22:20:18
【问题描述】:
我需要连续发出两个帖子请求。有一个异步“post form”函数,它使用“await”关键字启动请求,结果在“then”块中处理。
我尝试通过等待一个承诺来完成这个发布请求,其中我调用了上面提到的异步函数。问题在于,似乎无法在函数"then" 块内解决承诺。
我有一些示例代码来显示问题(查看 start() 函数的开始位置)。见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();
我怎样才能解决第一个承诺,还是不可能?还有其他解决方案吗? 我们的想法是在第一个请求解决后发出另一个发布请求。
【问题讨论】:
-
这里有很多错误,这不是 promises / async await 的工作原理
-
mainFunction()返回的 Promise 永远不会解决,这绝对不足为奇。没有尝试解决它。如果mainFunction()的目的是模拟一些异步过程,那么就直接写function mainFunction() { return Promise.resolve(); }吧。 -
async/await是.then()的替代语法。避免将两者混为一谈。
标签: javascript promise async-await