gpt4 book ai didi

javascript - 如何在没有嵌套回调的情况下处理获取的 promise ?

转载 作者:行者123 更新时间:2023-12-03 01:00:30 25 4
gpt4 key购买 nike

我猜想 fetch 返回了一个 promise 。但我该如何处理好呢?下面的代码不太有效。我收到 {message:“内部服务器错误自定义:TypeError:无法读取未定义的属性“then””}

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};
});
}

最佳答案

您收到该错误是因为您的 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 响应视为完全错误。我无耻地从他的博客中窃取了他的示例代码并将其添加到上面。

关于javascript - 如何在没有嵌套回调的情况下处理获取的 promise ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52645196/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com