承诺永远不会在javascript中得到解决
我有一个asyn函数,在这个函数中,我调用了另一个函数,该函数返回一个承诺,还调用了另一个异步函数。代码如下:承诺永远不会在javascript中得到解决,javascript,promise,async-await,html5-canvas,Javascript,Promise,Async Await,Html5 Canvas,我有一个asyn函数,在这个函数中,我调用了另一个函数,该函数返回一个承诺,还调用了另一个异步函数。代码如下: async function asyncAwaitRepeat(index) { if(index < 9) { await promise_animate(rectPointer); // the promise_animate return a promise await asyn
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);
动画函数本身是异步的,做了很多异步的事情
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");
if( rectArray[rectIndex].value > rectArray[rectIndex+1].value ) {
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
}
}
异步函数animate(rectIndex,animationPromiseCompleted){
如果(索引<8){
等待承诺(红色);
if(rectary[rectinex].value>rectary[rectinex+1].value){
等待承诺(红色);
//做一些异步的事情
等待动画(rectIndex+1,AnimationPromiseCompleted);//rectArray[rectIndex+1]。值){
等待承诺(红色);
//一些更异步的东西
}
等待承诺高亮度(绿色);
rectPointer=0;
AnimationPromiseCompleted(“动画功能已解决”)对于这个特定的示例,我会尝试类似的方法,这将确保在第一个承诺转移到下一个承诺之前解决它。您当前的承诺是并行运行的。根据您的数据,您可能不需要异步函数
(async (index) => {
if(index<9){
Promise.all([promise_animate(rectPointer),asyncAwaitRepeat(index + 1)]).then((values) => {
console.log(values);
});
}
});
(异步(索引)=>{
如果(索引){
console.log(值);
});
}
});
我不确定,但您可以尝试下面的代码。您可以调用resolve方法。它不会立即触发
function promise_animate (index) {
return new Promise((resolve) => {
animate(index, () => resolve());
})
}
我认为你的决心永远不会被召唤,所以你必须这样尝试:
function promise_animate (index) {
return new Promise(async(resolve) => {
resolve(await animate(index));
})
}
首先,欢迎来到社区。但我已经在做你说的:)@Yuseff不,你不是。这是最好的答案。此外,行可以缩短为animate(index,resolve)
非常感谢你的代码,我实现了你的版本,它正在工作。但是你说resolve永远不会被调用,不,这在调试器模式下不是真的,我看到它被调用了,但基督知道它为什么没有被调用,是np-Happy编码:-)动画(索引,()=>{resolve};
是个问题;它需要动画(索引,()=>{resolve()});
或动画(索引,()=>resolve());
或动画(索引,解析);
function promise_animate (index) {
return new Promise(async(resolve) => {
resolve(await animate(index));
})
}