最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - Using async-await with node-fetch does not return the response to the calling method - Stack Overflow

matteradmin2PV0评论

I have a function defined in a module that is supposed to do a fetch and return the response. I am having trouble returning the response from the fetch. The calling function gets the return value as "undefined".

I am new to JavaScript and Node so might need a little bit of hand-holding if you don't mind.

Calling function

async function executeTest() {
    try {
        const response = await bpc.postLendingApplication(
            blendConnection,
            loanData
        );
        console.log("Response from POST Loan: ", response);
    } catch (error) {
        console.log(error);
    }
}

Module function doing the fetch request

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

The console output is:

Processing POST Loan.
Status:  200
StatusText:  OK
OK:  true
Response from POST Loan:  undefined

As you can see, the fetch did what it was supposed to do and if I log the res.json() within the module method, it prints the payload. But I would like to return the error and response from the fetch so the module behaves as a generic method and the processing and error handling is done in the calling method.

I have a function defined in a module that is supposed to do a fetch and return the response. I am having trouble returning the response from the fetch. The calling function gets the return value as "undefined".

I am new to JavaScript and Node so might need a little bit of hand-holding if you don't mind.

Calling function

async function executeTest() {
    try {
        const response = await bpc.postLendingApplication(
            blendConnection,
            loanData
        );
        console.log("Response from POST Loan: ", response);
    } catch (error) {
        console.log(error);
    }
}

Module function doing the fetch request

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

The console output is:

Processing POST Loan.
Status:  200
StatusText:  OK
OK:  true
Response from POST Loan:  undefined

As you can see, the fetch did what it was supposed to do and if I log the res.json() within the module method, it prints the payload. But I would like to return the error and response from the fetch so the module behaves as a generic method and the processing and error handling is done in the calling method.

Share edited Apr 2, 2024 at 6:13 VLAZ 29.1k9 gold badges63 silver badges84 bronze badges asked Mar 22, 2020 at 16:52 Varun VermaVarun Verma 7242 gold badges13 silver badges22 bronze badges 4
  • You don't need async/await inside then. – Daniyal Lukmanov Commented Mar 22, 2020 at 16:57
  • In your case you either should return Promise or rewrite your function in other way. – Daniyal Lukmanov Commented Mar 22, 2020 at 16:58
  • @DaniyalLukmanov Nope. async function automatically returns a promise. Your return value is the resolution of it. – Chance Commented Mar 22, 2020 at 17:13
  • @Chance you didn't get what I mean. – Daniyal Lukmanov Commented Mar 22, 2020 at 22:31
Add a ment  | 

2 Answers 2

Reset to default 7

When you mark a function as async, JavaScript will always return a Promise, thus making it asynchronous. When you return a value, it is resolving the Promise. Using await inside of these functions "pauses" execution (it is technically creating a new function for code that occurs after the await) until the awaited Promise is resolved, standing in place of the usage of then(callback). As such, you don't need then inside of any async function.

You do, however, need to treat your own async function as a 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
}

When calling postLendingApplication(connection, data) make sure that you are either using await, if inside an async function or postLendingApplication(connection, data).then(callback) as the return value will be a Promise.

postLendingApplication(connection, data).then(callback).catch(errHandler)

You forget to return form function. return await fetch(connection.url, { You dont need async-await in then function. You can return 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();
    });
}
Post a comment

comment list (0)

  1. No comments so far