【发布时间】:2020-06-23 00:29:35
【问题描述】:
当我向服务器发出请求时,数据作为包含正确数据的承诺(如预期)返回,但由于某种原因,程序无法正确执行。
此外,该程序在我将其上传到 Zeit 之前就可以运行。
获取请求:
1) 我知道我不需要“内容类型”:“应用程序/json”。删除它不会影响程序。
2) 这是一个 GET 请求,端点工作正常。另外,当我在 Postman 中执行同样的请求时,我得到了正确的结果。
// CODE ABOVE DOES NOT MATTER
.then( ([hours, employees, dayLabor]) => {
// hours, employees, and dayLabor are empty lists for this exercise '[]'
let business = fetch(`${config.URL}/${TokenService.getId()}`,
{
headers: {
'content-type': 'application/json',
'table':'business',
'Authorization':`bearer ${TokenService.getAuthToken()}`
}
})
.then(data => {
console.log('business: ',data, ' or ', data.json());
if (!data.ok){
return data.json().then(e => Promise.reject(e));}
return data.json();
});
return Promise.all([business, hours, employees, dayLabor]);
})
.then( ([business, hours, employees, dayLabor]) => {
// THIS is never executed?
console.log('completed');
//fetch has been completed and the state has been updated so set "fetched" to true
this.setState({business, hours, employees, 'dayLabor': dayLabor.length>0? this.sort(dayLabor):[], fetched: true});
})
.catch(error => {
console.error({error});
});
输出结果(出于隐私原因删除了网址):
business:
Response {type: "cors", url: "https://xxxxxx.herokuapp.com/1", redirected: false, status: 200, ok: true, …}
type: "cors"
url: "https://xxxxxxxx.herokuapp.com/1"
redirected: false
status: 200
ok: true
statusText: "OK"
headers: Headers {}
body: (...)
bodyUsed: true
__proto__: Response
or
Promise {<pending>}
__proto__: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: Array(1)
0: {id: 1, business_name: "Fake Company Inc"}
length: 1
__proto__: Array(0)
我想访问“[[PromiseValue]]”中的对象。我很困惑为什么这不起作用,尤其是当我在本地运行它时它确实起作用了?似乎问题在于“业务”变量或“Promise.all”没有等待承诺解决。
任何帮助将不胜感激,我一直在搜索,但找不到任何解决方案。
【问题讨论】:
标签: javascript reactjs promise frontend es6-promise