gpt4 book ai didi

javascript - NodeJS 异步函数不暂停

转载 作者:搜寻专家 更新时间:2023-11-01 00:36:04 25 4
gpt4 key购买 nike

我有一个异步函数,它使用 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

最佳答案

您的 runCypherQuery 目前没有返回任何特殊信息。为了 await 它,您需要明确指定它返回一个 Promise,一旦 request 完成,它就会解析。只是 awaiting 一个 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)
})
})
}

关于javascript - NodeJS 异步函数不暂停,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51684564/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com