在使用promisethen时,是否可能停留在单击事件调用堆栈中?

时间:2022-08-10 00:01:23

The play() method on an audio element must be triggered by a user initiated event but it seems like the .then used in my click event breaks the call stack. I have to use .then in this situation.

音频元素上的play()方法必须由用户发起的事件触发,但它看起来像。然后在我的点击事件中使用的是调用堆栈。在这种情况下,我必须使用。

The ng-click calls open(file) in its controller which is just a reference to open() from my "player" service.

ng-click在其控制器中调用open(file),它只是对我的“player”服务中的open()的引用。

open() from "player" service:

open()从“玩家”服务:

this.open = function(file){
  storage.getUrl(file)
    .then(function(url){
      audio.playUrl(url);
    });
};

getUrl() just returns a string promise.

getUrl()只返回一个字符串承诺。

playUrl() from "audio" service:

playUrl()从“音频”服务:

function playUrl(url){
  audio.src = url;
  audio.play();
};

Now I can audio.play() just fine from another method in my "audio" service that doesn't use any promises. Can I make this work from open()?

现在我可以使用audio.play()了,这是我的“audio”服务中不使用任何承诺的另一个方法。我可以从open()开始工作吗?

1 个解决方案

#1


2  

Is it possible to stay inside click event call stack when using promise.then?

在使用promisethen时,是否可以停留在单击事件调用堆栈的内部?

Not in this case. It would be possible if the promise completed synchronously, but usually promises are used for situations that will complete asynchronously, and that's the case here.

在这种情况下。如果承诺是同步完成的,这是可能的,但是通常承诺用于异步完成的情况,这里就是这样。

Instead, you'd want to complete the storage.getUrl part before the click occurs (preload it), so that you can then play during the user event.

相反,您需要完成存储。getUrl部分在单击发生之前(预加载它),这样您就可以在用户事件期间运行。

#1


2  

Is it possible to stay inside click event call stack when using promise.then?

在使用promisethen时,是否可以停留在单击事件调用堆栈的内部?

Not in this case. It would be possible if the promise completed synchronously, but usually promises are used for situations that will complete asynchronously, and that's the case here.

在这种情况下。如果承诺是同步完成的,这是可能的,但是通常承诺用于异步完成的情况,这里就是这样。

Instead, you'd want to complete the storage.getUrl part before the click occurs (preload it), so that you can then play during the user event.

相反,您需要完成存储。getUrl部分在单击发生之前(预加载它),这样您就可以在用户事件期间运行。