Var*_*rma 1 javascript fetch node.js async-await node-fetch
我在模块中定义了一个函数,该函数应该执行获取并返回响应。我在从 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);
}
}
Run Code Online (Sandbox Code Playgroud)
执行获取请求的模块函数
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;
});
}
Run Code Online (Sandbox Code Playgroud)
控制台输出是:
Processing POST Loan.
Status: 200
StatusText: OK
OK: true
Response from POST Loan: undefined
Run Code Online (Sandbox Code Playgroud)
如您所见,fetch 完成了它应该做的事情,如果我在模块方法中记录 res.json(),它会打印有效负载。但我想从 fetch 返回错误和响应,以便模块表现为通用方法,并且处理和错误处理在调用方法中完成。
当您将 a 标记function为 时async,JavaScript 将始终返回 a 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
}
Run Code Online (Sandbox Code Playgroud)
调用时postLendingApplication(connection, data),请确保您正在使用await,如果在 an 内部async function或postLendingApplication(connection, data).then(callback)作为返回值将是 a Promise。
postLendingApplication(connection, data).then(callback).catch(errHandler)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7038 次 |
| 最近记录: |