首页 > 解决方案 > 打字稿等待在回调中不起作用

问题描述

我有两个函数,我通过回调调用cbf()func()我正在使用 await 但after callback首先。

function cbf(name, callback: Function) {
    console.log(name)
    callback("123")
}

function async func() {
    await cbf("alice", function(aa) {
        console.log(aa)
    })
    console.log("after callback")  
}

标签: javascripttypescriptasynchronousasync-await

解决方案


你应该使用 Promise

function cbf(x) { 
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(x);
    }, 2000);
  });
}

async function f1() {
  var x = await cbf(10);
  console.log(x); // 10
}

f1();


推荐阅读