我有一个异步函数,该函数使用await调用另一个异步函数,但是第一个函数不等待第二个函数完成。
module.exports.checkNewUser = async(uuid) => {
const getUserQuery = `MATCH (n:USER {uuid:"${uuid}"}) RETURN n;`
console.log(getUserQuery)
console.log('1')
const result = await this.runCypherQuery(getUserQuery)
console.log('3')
console.log('results:')
console.log(JSON.stringify(result, null, indent))
if(result !== []) throw new Error('user already exists')
return
}
const request = require('request')
const uri = 'http://localhost:7474/db/data/transaction/commit'
module.exports.runCypherQuery = async(query) => {
const headers = { Authorization: 'Basic xxx' }
const json = {statements: [{statement: query, parameters: {}}]}
//console.log(json)
request.post({uri: uri, headers: headers, json: json}, (err, res, body) => {
if(err) throw new Error(err.message)
//console.log(body)
const data = body.results[0].data
console.log('data:')
console.log(data)
console.log('2')
return data
})
}
终端输出为:
MATCH (n:USER {uuid:"xxx"}) RETURN n;
1
3
results:
undefined
data:
[]
2
答案 0 :(得分:3)
您的runCypherQuery
目前未返回任何特殊信息。为了await
,您需要明确指定它返回一个Promise
,一旦request
完成,它就会解析。 await
函数async
并不意味着async
函数在解析之前会等待所有异步操作完成。将基于回调的request
转换为Promise
并返回该Promise
,以便可以正确await
对其进行编辑:
module.exports.runCypherQuery = (query) => {
const headers = { Authorization: 'Basic xxx' }
const json = {statements: [{statement: query, parameters: {}}]}
return new Promise((resolve, reject) => {
request.post({uri: uri, headers: headers, json: json}, (err, res, body) => {
if(err) reject(err.message)
//console.log(body)
const data = body.results[0].data
console.log('data:')
console.log(data)
console.log('2')
resolve(data)
})
})
}
答案 1 :(得分:0)
出于完整性考虑,并根据@CertainPerformance给出的建议,此版本在异步函数中使用request-promise
包。
const rp = require('request-promise')
const uri = 'http://localhost:7474/db/data/transaction/commit'
module.exports.runQuery = async(query) => {
const headers = { Authorization: 'Basic xxx' }
const json = {statements: [{statement: query, parameters: {}}]}
//console.log(json)
const body = await rp.post({uri: uri, headers: headers, json: json})
return body.results[0].data
}