javascript 回调无法以异步方式工作

标签 javascript

当我试图理解 js 回调时,我遇到了这个问题。 在这里,我尝试在 2500 ms 之后提醒 aa,即当 aa 的值已解析时,但我得到的结果为 1。为什么? 我认为 aa 在这里未定义,但 b() 在调用堆栈中。它应该解析 aa 的实际值。 如果我错了,请纠正我。

function a(b){
    var aa = b();
    
    setTimeout(function(){
    alert(aa)
    },3000)
    }
    
    function b() {
    return setTimeout(function() {
    return 'alert this value !';
    },2500)
    }
    
    a(b);

最佳答案

您不能从这样的异步函数返回值。获得类似行为的一种方法是使用 promises :

async function a(b){
    var aa = await b();

    setTimeout(function(){
      alert(aa)
     },3000)

)

function b() {
  return new Promise( (resolve, reject) => {
    setTimeout(function() {
      resolve( 'alert this value !' );
    },2500)

  }
}

a(b);

当您没有可用的 async/await 时,您还可以使用 Promise 的 then() 回调a():

function a(b){
    b().then( (value) => {
       setTimeout(function(){
         alert(value)
       },3000)
    });
)

关于javascript 回调无法以异步方式工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44858705/

相关文章:

javascript - 网络 worker 中的 getUserMedia

php - 使用 PHP + AJAX 发送帖子

javascript - 将 html 表数据转换为在 javascript 循环中运行

javascript - 无法更改 D3 中的 X/Y 轴值

javascript - 如何仅在从 REST Api 获取所有数据后才执行函数

javascript - 使用 jQuery 的 Ajax 日历导航

javascript - grunt exec 卡住,期待来自 django collectstatic 的 0 状态代码

Javascript 分割字符串在 .但不是 。引号后

javascript - 等到处理完成后再导出 Node.js 模块?

JavaScript:Promise.all 结果中有 1 个未定义值