[英]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.