[英]Using async-await with node-fetch does not return the response to the calling method
我在模块中定义了一个函数,该函数应该执行获取并返回响应。 我在从 fetch 返回响应时遇到问题。 调用函数将返回值设为“未定义”。
我是 JavaScript 和 Node 的新手,所以如果你不介意的话,可能需要一点帮助。
调用函数
async function executeTest() {
try {
const response = await bpc.postLendingApplication(
blendConnection,
loanData
);
console.log("Response from POST Loan: ", response);
} catch (error) {
console.log(error);
}
}
执行获取请求的模块函数
const fetch = require("node-fetch");
async function postLendingApplication(connection, data) {
console.log("Processing POST Loan.");
await fetch(connection.url, {
method: "POST",
headers: connection.headers,
body: data,
}).then(async res => {
console.log("Status: ", res.status);
console.log("StatusText: ", res.statusText);
console.log("OK: ", res.ok);
return await res;
});
}
控制台输出是:
Processing POST Loan.
Status: 200
StatusText: OK
OK: true
Response from POST Loan: undefined
如您所见,fetch 完成了它应该做的事情,如果我在模块方法中记录 res.json(),它会打印有效负载。 但我想从 fetch 返回错误和响应,以便模块表现为通用方法,并且处理和错误处理在调用方法中完成。
当您将function
标记为async
,JavaScript 将始终返回一个Promise
,从而使其异步。 当您返回一个值时,它正在解析Promise
。 在这些函数中使用await
“暂停”执行(从技术上讲,它为await
之后发生的代码创建一个新函数),直到等待的Promise
得到解决,代替then(callback)
。 因此,您不需要then
在任何async function
。
但是,您确实需要将自己的async function
视为Promise
。
const fetch = require("node-fetch");
async function postLendingApplication(connection, data) {
try {
console.log("Processing POST Loan.");
// the await eliminates the need for .then
const res = await fetch(connection.url, {
method: "POST",
headers: connection.headers,
body: data,
})
// this code is resumed once the fetch Promise is resolved.
// res now has a value.
console.log("Status: ", res.status);
console.log("StatusText: ", res.statusText);
return res;
}
catch(err) {
// because the promise could error, it is advised to use
// try/catch. With a Promise, you would .then(cb).catch(errHandler)
// but async/await doesn't utilize callbacks.
// perform error handling or you can bubble it up.
throw err
}
调用postLendingApplication(connection, data)
,请确保您使用await
,如果在async function
或者postLendingApplication(connection, data).then(callback)
作为返回值将是Promise
。
postLendingApplication(connection, data).then(callback).catch(errHandler)
您忘记返回表单功能。 return await fetch(connection.url, {
你不需要在then
函数中使用async-await
。你可以返回res.json()
const fetch = require("node-fetch");
async function postLendingApplication(connection, data) {
console.log("Processing POST Loan.");
return await fetch(connection.url, {
method: "POST",
headers: connection.headers,
body: data,
}).then(res => {
console.log("Status: ", res.status);
console.log("StatusText: ", res.statusText);
console.log("OK: ", res.ok);
return res.json();
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.