![](/img/trans.png)
[英]code after await axios post call is not running, no error in catch block
[英]Axios code not running after `.then`
我是 react/nodejs/express/javascript 的新手,遇到了以下問題:
我想獲得一個數字,然后發布該數字 + 1,然后我想使用該數字( newFreshId
)創建一個新的 js object 並且我想添加它以將該事件添加到我的schedulerData
。 當我嘗試運行代碼時,我可以獲取並發布到/api/num
,但是.then(function(response) {
之后的所有內容似乎都沒有運行。
我想按順序執行此操作,所以我在每個任務之后使用.then
,這樣我就不會遇到問題。
我還嘗試刪除所有.then
以支持等待值更改的 while 循環。 這也沒有用。
代碼:
客戶:
this.newEvent = (schedulerData, slotId, slotName, start, end, type, item) => {
let newFreshId = 0;
let newEvent = {}
axios.get("/api/num").then(function(response) {
newFreshId = response.data[0] + 1;
// console.log(newFreshId);
}).then(function() {
axios.post("/api/num", {
id: newFreshId
}).then(function(response) {
console.log(response)
// handle success
newEvent = {
id: newFreshId,
title: this.state.title,
start: start,
end: end,
resourceId: slotId
};
schedulerData.addEvent(newEvent);
this.setState({
viewModel: schedulerData
});
// while(JSON.stringify(newEvent) === '{}'){
// console.log('waiting')
// }
console.log(newEvent)
schedulerData.addEvent(newEvent);
console.log(newEvent)
this.setState({
viewModel: schedulerData
});
})
})
};
服務器:
app.get('/api/num', function(req, res) {
//console.log(require('./number.json'))
var fs = require('fs')
fs.readFile('./number.json', {encoding: 'utf-8'}, function(err,data){
if (!err) {
//console.log('received data: ' + JSON.parse(data));
res.json(JSON.parse(data))
} else {
console.log(err);
}})
})
app.post('/api/num', function(req, res) {
var id = req.body.id
var fs = require('fs');
fs.writeFileSync("./number.json", "[ "+id+" ]", function(err) {
if(err) {
return console.log(err);
}
res.status(200)
})
})
感謝所有的幫助:)
fs.writeFileSync
沒有回調,所以你添加的函數永遠不會被執行: https : fs.writeFileSync
這意味着永遠不會將響應發送回客戶端,並且永遠不會解析 axios 承諾。
嘗試使用帶有回調的fs.writeFile
: https : fs.writeFile
在出現錯誤的情況下發送響應也是一個好主意。
app.post('/api/num', function(req, res) {
var id = req.body.id
var fs = require('fs');
fs.writeFile("./number.json", "[ "+id+" ]", function(err) {
if(err) {
console.log(err);
return res.status(200)
}
res.status(200)
})
})
最后,盡管在這種情況下對您沒有幫助,但您應該在 axios 鏈的最尾端添加一個.catch
。 承諾鏈中發生的任何錯誤都會在那里結束。
一個例子:
axios.get(specs).then(someFunction).catch(e => console.error(e));
對我來說,我遇到了同樣的問題,我發現這是因為我在發出帖子請求后使用了一些重定向
window.location.href = "/{redirect to some rout}"
這使控制台立即更改,因此除非我刪除重定向,否則我看不到 then 響應。
我也遇到了無法運行 .then() 或 .catch() 代碼的問題
const fetch = async() => { axios.get("https://jsonplaceholder.typicode.com/todos/1") .then((res) => { console.log(res) }) .catch(err => { console.log(err) }) }
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.24.0/axios.min.js"></script>
const axios = require('axios').default;
像這樣使用它
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.