【发布时间】:2020-11-02 20:42:18
【问题描述】:
下面的异步函数返回2个回调,所以我做了我通常做的返回响应
- 在获取之前添加了返回
- 在结果前添加了 return (
json.access_token)
但这次console.log(httpResponse, 'fetch json') 在控制台上未定义,console.log(json.access_token) 返回正确的值。
我需要改变什么?
来自客户
GetJSON(NewURLCode).then(httpResponse => {
console.log(httpResponse, 'fetch json')
}
来自服务器
GetJSON(NewURLCode){
return fetch("https://accounts.google.com/o/oauth2/token", {
"method": "post",
"headers": {
"Content-Type": 'application/x-www-form-urlencoded'
},
'body': data
}).then((httpResponse) => {
if (httpResponse.ok) {
return httpResponse.json();
} else {
return Promise.reject("Fetch did not succeed");
}
}).then((json) => {
console.log(json.access_token)
return json.access_token
}).catch(err => console.log(err));
}
与前面的函数不同,下面的函数只有一个promise,并从客户端返回正确的对象
客户
insert_coll ('Token',toInsert).then((ins_result) => {consule.log(ins_result)}
后端
insert_coll{
return wixData.update(myCollection, toUpdate, options)
.then( ( results) => {
let item = results; //see item below
return results
} )
.catch( (err) => {
let errorMsg = err;
} );
}
}
【问题讨论】:
-
你在
httpResponse.json();和Promise.reject(…)前面缺少returns -
你不是
returninghttpResponse.json()- 或Promise.reject()在你的第一个然后阻止 -
我编辑了我的 Q 并在
httpResponse.json()之前添加了一个返回语句,但在客户端控制台上继续获得 null,在服务器控制台上继续获得 JSON。
标签: javascript asynchronous async-await velo