使用javascript promise检查变量

时间:2018-01-25 16:04:59

标签: javascript promise

我有两个变量需要满足某些值,然后调用一个函数。其中一个变量在js-animation完成后从onComplete调用中设置。一旦视频文件完成预加载,则调用另一个。我的问题是,我不知道哪一个会被称为第一个。因此,我想检查两个值是否符合承诺。 它们都在两个不同的回调函数中设置它们的值。 我有这个,但我不明白如何使用Promise回调。

// Callback 1:
function nextSlide(event){
   finishedAnim = true;
};

// Callback 2:
function handleNextFileComplete(event) {         
   nextVideoEl.src = nextVideo;
   nextfileLoaded = "complete";
};

Promise.all([

]).then(() => {
   slider.next();
});  

2 个答案:

答案 0 :(得分:1)

One solution would be using promises instead of control variables. Let's say you have a function to start the animation and other to start loading the video file.

function startAnimation() {
    return new Promise((resolve, reject) => {
         // Start the animation and pass the onAnimationCompleted callback
         function onAnimationCompleted(event) {
             resolve();
         }
    });
}

function startLoadingVideo() {
    return new Promise((resolve, reject) => {
         // Start loading the video and pass the onVideoLoaded callback
         function onVideoLoaded(event) {
              resolve();
         }
    });
}

Now you can call both functions and use the function Promise.all() to handle the promises. The calling method would be something like:

let animationPromise = startAnimation();
let videoPromise = startLoadingVideo();

Promise.all([animationPromise, videoPromise])
    .then(() => slider.next());

答案 1 :(得分:0)

我意识到这种复杂的情况。 首先我有这个代码的计时器:

#input
ls0 = 'x'
ls1 = ('expt', 'x', 2)
ls2 = ('+', ('expt', 'x', 2), ('expt', 'y', 2))
ls4 = ('/', ('expt', 'x', 5), ('expt', ('-', ('expt', 'x', 2),1), ('/', 5, 2)))

#expected output
print(depth(ls4)) #expected output 4
print(depth(ls2)) #expected output 2
print(depth(ls1)) #expected output 1

#function definition
def depth(expr):
    a = []
    for j in range(len(expr)):
        if isinstance(expr,(list,tuple)) == 0:
            a.append(0)
            if len(a) == len(expr):
                return max(a)
        else:
            a.append(1 + depth(expr[j]))

然后我用这段代码预加载视频:

TweenMax.delayedCall(7.3, delayCallComplete);
function delayCallComplete(event){
        finished = true;
    };

我想在调用包含slider.next();的函数之前检查这两种情况是否已经发生。