Ann*_*aia 5 javascript jquery promise reactjs es6-promise
我需要在我的 API 上发布一些东西。我有这个功能可以正常工作:
TradeContainer.js:
callApi(action){
var actionInfo = {
user_id: this.props.currentUser.id,
action: action
}
fetch('http://localhost:3000/actions', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(actionInfo)
})
.then(res => res.json())
.then(data => console.log(data))
}
Run Code Online (Sandbox Code Playgroud)
我想将 fetch() 移动到我进行所有 API 调用的另一个文件。在那个文件中,我已经有几个 fetch 函数(使用 get 方法)并且它们工作正常。但是,当我使用 post 方法将此 fetch() 移动到该文件时,出现错误:
类型错误:无法读取未定义的属性“then”
我的代码:
TradeContainer.js:
import { saveAction } from '../components/apiCalls.js'
callApi(action){
var actionInfo = {
user_id: this.props.currentUser.id,
action: action
}
//this is fetch() function that i moved to apiCalls.js file.
//And this two lines of code throw an error.
saveAction(actionInfo)
.then(data => console.log(data))
}
Run Code Online (Sandbox Code Playgroud)
apiCalls.js
export function saveAction(actionInfo){
fetch('http://localhost:3000/actions', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(actionInfo)
})
.then(res => res.json())
}
Run Code Online (Sandbox Code Playgroud)
.then(res => res.json()) 返回 "ok" 和 200. 但saveAction(actionInfo)返回undefined。怎么来的?
该函数saveAction不返回任何内容(特别是 - 不返回承诺),因此您不能then在该函数上使用:
export function saveAction(actionInfo){
fetch({
...
})
.then(res => res.json())
}
Run Code Online (Sandbox Code Playgroud)
您可以返回fetch(这是一个承诺),然后您可以then在该函数上使用:
export function saveAction(actionInfo){
return fetch({
...
})
.then(res => res.json())
}
Run Code Online (Sandbox Code Playgroud)