javascript - 打字稿等待在回调中不起作用
问题描述
我有两个函数,我通过回调调用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")
}
解决方案
你应该使用 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();
推荐阅读
- javascript - 在 c# 中使用 javascript 数组填充剃刀表
- ios - 如何在拆分视图的详细信息区域限制MessageKit的输入栏
- grails - Grails 升级 - 1.3.7 到 2.4.1 以兼容 Java 1.8。如何在类路径中添加自定义 jar
- flyway - 是否 Flyway 工具支持 Oracle E-Business Suite 中的 .rdf、.rtf、.xml、.pks、.pkb 等扩展名 --> 财务管理
- javascript - 从 jQuery 运行 PHP 脚本,然后提交表单
- node.js - 直接使用 chromedriver 运行 webdriver.io,而不是使用 selenium 服务器
- php - 登录后,如何在 laravel 中使用 ajax post 请求?
- apache - odoo 11 在端口 8069 上被谷歌索引
- ios - Swift 中 JTAppleCalendar 中日期标签下的月份名称
- c# - C# 无法连接到远程服务器(WebException、SocketException)