简体   繁体   English

异步功能完成后,如何开始执行功能? 在这种情况下,诺言不起作用

[英]How can I start performing function after async function is completed? A promise is not working in this case

I would like to perform two function simultaneously. 我想同时执行两个功能。 But one of them is using the value from the second one(async function) in callback. 但是其中之一正在回调中使用第二个值(异步函数)中的值。

const asyncFunction = '' // it is fetch function and i need this function 
 // to complete before send() function perform
const send ='' // it sends information from asyncFunction , so it has to 
//  be perform after asyncFunction is completed
asyncFunction()
document.querySelector('.js-btn').addEventListener('click', send()) 
// I would like to listen immediately when page is load, and send an 
// information when asyncFunction is complete

Using promises i can listen for click only when asyncFunction is completed, so if user click a btn before asyncFunction is complete it doesn't perform an event 使用Promise我只能在asyncFunction完成时监听点击,因此,如果用户在asyncFunction完成之前单击btn,则不会执行事件

What i would like to do is to listen for an action immediately when page is load, but send() function has to wait until asyncFunction is completed and then perform. 我想做的是在页面加载时立即监听动作,但是send()函数必须等到asyncFunction完成然后执行。

Please help me:) 请帮我:)

Possible solutions: 可能的解决方案:

  1. disable the body and show "please wait" until the asyncFunc is done. 禁用主体并显示“请稍等”,直到asyncFunc完成。

  2. make the body invisible until the asyncFunc is done. 在asyncFunc完成之前使身体不可见。

  3. disable the send button until the asyncFunc is done. 禁用发送按钮,直到asyncFunc完成。

  4. add an anonymous function to the send button. 向发送按钮添加一个匿名函数。 Remove that function on click and start checking every 10ms if the async has finished and then then performs the send() 单击删除该函数,并每隔10ms开始检查一次异步是否完成,然后执行send()

  5. add two bools. 加两个布尔。 let asyncFuncFinished = false; let sendFinished = false; now you cann add to asyncFunc and send if (asyncFuncFinished && sendFinished) send(); 现在您不能添加到asyncFunc并发送if (asyncFuncFinished && sendFinished) send();

In this scenario your send function have to wait till asyncFunction be done. 在这种情况下,您的发送功能必须等到asyncFunction完成。 So the click event should be set after asyncFunction is done. 因此,应在asyncFunction完成后设置click事件。 It doesn't make sense when you don't have the result of asyncFunction set a click event. 当没有asyncFunction的结果设置click事件时,这没有任何意义。

You can set a click event on page load to show the user a 'Please wait...' message (or whatever), and in callback of asyncFunction (or use promises) remove that click event and set another one to fire send function. 您可以在页面加载时设置一个click事件,以向用户显示“请稍候...”消息(或其他内容),然后在asyncFunction的回调中(或使用promises)删除该click事件,并设置另一个事件来触发send函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM