JavaScript:如何使用异步方法?

标签 javascript node.js asynchronous async-await

我想得到结果:

1
2
3

怎么做?

我尝试了几种实现选项,但它们都没有产生我想要的相同结果。

如果使用:

var aaa = {
    line: function () {
        console.log(1)
        aaa.RF();
        console.log(3)
    },
    RF: async function () {
        await jsonfile.readFile(file, function(err, obj) {
            console.log(2)
        })
    }
}
aaa.line()

结果:

1
3
2

如果

console.log(4)
async jsonfile.readFile(file, function(err, obj) {
    await console.log(5)
})
console.log(6)

结果错误

如果

console.log(1)
async function a() {
    await jsonfile.readFile(file, function(err, obj) {
         console.log(2)
    })
}
a()
console.log(3)

结果:

1
3
2

最佳答案

您需要等待aaa.RF()。如果不添加 await,它仍然将 async 函数视为异步并继续。

var aaa = {
    line: async function () {
        console.log(1)
        await aaa.RF();
        console.log(3)
    },
    RF: async function () {
        await jsonfile.readFile(file, function(err, obj) {
            console.log(2)
        })
    }
}
aaa.line()

关于JavaScript:如何使用异步方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44708328/

相关文章:

javascript - 在模块作用域中声明的变量不是模块对象的属性吗?

json - 无法访问最初作为 JSON 对象发送的字符串(即 [ object Object ])内的数据

c# - 锁定 C# switch case 的首选方式

scala - 优雅的 Iteratee -> 枚举器 "forwarding"正在运行

javascript - 为什么我完成的种子(有时)没有写入磁盘?

javascript - 修复后的 Meteor-React 错误 : Target Container is not a DOM element,

javascript - 在node.js中使用GM裁剪成带圆圈的图片

javascript - 获取索引处字符的 ANSI 颜色

loops - While 循环使用 Await Async。

javascript - 如何删除 span 类中文本字符串的一部分