我猜fetch会返回一个承诺。但是我如何处理好呢?下面的代码无法正常工作。我得到{message: "Internal server error custom: TypeError: Cannot read property 'then' of undefined"}
。
exports.handler = (event, context, callback) => {
try {
getDiscourseId(username, callback).then((userId) => {
callback(null, {
statusCode: 200,
headers: {},
body: JSON.stringify({
userId: userId
})
});
});
} catch (error) {
callback(null, {
statusCode: 500,
headers: {},
body: JSON.stringify({
message: "Internal server error custom: " + error
})
});
}
};
function getDiscourseId(username) {
console.log({username: username, discourseApiKey: discourseApiKey, discourseApiUser: discourseApiUser})
fetch(`https://${domain}/users/${username}.json?api_key=${discourseApiKey}&api_username=${discourseApiUser}`, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json'
},
method: 'GET',
})
.then(response => {
return response.json();
})
.then(data => {
if (data) {
return data.user.id;
}
})
.catch(err => {
return {err: err};
});
}
答案 0 :(得分:1)
由于getDiscourseId
函数未返回值,因此出现该错误。
如果您在return
通话之前添加关键字fetch(...)
,则应该开始取得进展。
您可能还想从.catch
内部删除getDiscourseId
,而是将其添加到处理程序中getDiscourseId
的通话的末尾:
exports.handler = (event, context, callback) => {
getDiscourseId(username)
.then((userId) => {
callback(null, {
statusCode: 200,
headers: {},
body: JSON.stringify({
userId: userId
})
});
})
.catch(error => {
callback(null, {
statusCode: 500,
headers: {},
body: JSON.stringify({
message: "Internal server error custom: " + error
})
});
});
};
function getDiscourseId(username) {
console.log({username: username, discourseApiKey: discourseApiKey, discourseApiUser: discourseApiUser})
return fetch(`https://${domain}/users/${username}.json?api_key=${discourseApiKey}&api_username=${discourseApiUser}`, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json'
},
method: 'GET',
})
.then(response => {
if (!response.ok) { // h/t TJ Crowder
throw new Error("Failed with HTTP code " + response.status);
}
return response.json();
})
.then(data => {
if (data) {
return data.user.id;
}
});
}
编辑:TJ Crowder是正确的,您可能希望将4xx和5xx响应视为完整的错误。我毫不客气地从他的博客中窃取了他的示例代码,并将其添加到上面。
答案 1 :(得分:0)
在返回response.json()时停止。这将返回一个承诺,可以使用.then。
您将返回.then不能使用的userId。
如果您在返回response.json()处停止,则可以使用已有的'.then'语句(data.user.id => ...)。