我做一个POST api请求到/api/mycode.js
- 执行外部API调用(使用body.value)
- 保存到数据库
- res。将"ok", "error"等发送回原始POST请求,在那里我根据字符串 处理它
我尝试在.then
内使用async function
,但它似乎不起作用,这是mycode.js:
import { connectToDatabase } from "@/utils/mongodb"
const apiKey = process.env.API_KEY
export default async function (req, res) {
const { db } = await connectToDatabase()
var token = JSON.stringify(objtoken.accessToken, null, 2)
if (req.method === 'POST') {
const body = JSON.parse(req.body)
let itemId = body.id
// EXTERNAL API
var url = <external API url query>
fetch(url, {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
}
}).then(responseJson => {
console.log(responseJson)
if (responseJson.status >= 200 && responseJson.status < 300) {
saveToDb()
}else{
throwError()
}
}).catch(err => {
console.log(err)
});
const saveToDb = async () => {
// save logic for mongodb here
await db.collection('mycollection').updateOne etc...
res.send({ risp : 'ok' })
}
const throwError = () => {
res.send({ risp : 'error' })
}
}
res.end()
}
您需要通过await saveToDb()
或saveToDb().then()
而不仅仅是saveToDb()
来调用它,因为这是async
声明的函数,如果只是调用返回Promise
,则应该是await
ed。
也可以在try...catch
块中使用await fetch()
,而不是使用fetch().then()
,这将使代码更清晰。
try {
const resp = await fetch(...);
if (resp.status >= 200 && resp.status < 300) {
await saveToDb();
} else {
throwError();
}
} catch(e) {
// error
}