我想得到结果:
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/