如何解决承诺永远不会在 javascript 中得到解决
我有一个异步函数,我在其中调用另一个返回承诺的函数,并调用另一个异步函数。代码如下:
async function asyncAwaitRepeat(index) {
if(index < 9) {
await promise_animate(rectPointer); // the promise_animate return a promise
await asyncAwaitRepeat(index + 1); // but my promise_animate never gets resolved
}
}
asyncAwaitRepeat(asyncAwaitRepeatindex);
因为我有一些异步代码要执行,所以我不能直接调用 resolve()。 所以我使用回调
function promise_animate (index) {
return new Promise((resolve) => {
animate(index,() => {resolve}); // since animate function is a asynchronous so we
//cannot directly resolve() it
})
}
和 animate 函数本身是异步的,做一堆异步的事情
async function animate(rectIndex,animationPromiseFulfilled) {
if(rectIndex < 8) {
await promise_hightlight(rectIndex,"red");
if( rectArray[rectIndex].value > rectArray[rectIndex+1].value ) {
await promise_hightlight(rectIndex,"red");
// doing a bunch of asynchronous stuff
await animate(rectIndex+1,animationPromiseFulfilled); // << Here i call the
// function recursively
}
else if(rectIndex == 8) {
await promise_hightlight(rectIndex,"red");
// some more asynchronous stuff
}
await promise_hightlight(rectIndex,"green");
rectPointer = 0;
animationPromiseFulfilled("the animation function resolved");//<< the promise
//resolve done
}
}
但是 fullfiled() 没有做它的工作,也没有解决。请帮忙
解决方法
我认为你的决心永远不会被召唤,所以你必须这样尝试:
function promise_animate (index) {
return new Promise(async(resolve) => {
resolve(await animate(index));
})
}
,
对于这个特定的例子,我会尝试这样的事情,这将确保第一个承诺在转移到下一个承诺之前得到解决。您目前的承诺是并行运行的。根据您的数据,您可能不需要异步函数。
(async (index) => {
if(index<9){
Promise.all([promise_animate(rectPointer),asyncAwaitRepeat(index + 1)]).then((values) => {
console.log(values);
});
}
});
,
我不确定,但你能试试下面的代码吗?您可以调用解析方法。它不会立即触发。
function promise_animate (index) {
return new Promise((resolve) => {
animate(index,() => resolve());
})
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。