lnl
lnl

Reputation: 367

How to make `return` respecting async/await in JS?

I'm trying to make this code (a class method) returning a String.

async sign() {
    const txt = 'ddddd';
    const result = await crypto.createHash('md5').update(txt, 'binary').digest('hex');
    return result;
}

The problem is that it ignores await and returns a Promise. This function's returned value is used as a HTTP request header, and while npmlog says it's

apisign: Promise { 'faaa3f1409977cbcd4ac50b5f7cd81ec' }

in network traffic caught by Wireshark I see

apisign: [object Promise]

How do I make return respecting await, or how should I write it so it returns a String?

Upvotes: 3

Views: 922

Answers (3)

Kuldeep Bhimte
Kuldeep Bhimte

Reputation: 959

You will have to await the response of a async function.

const getURL = (title, page) => `https://jsonmock.hackerrank.com/api/movies/search/?Title=${title}&page=${page}`


const callService = async (title, page) => {
  let response = await fetch(getURL(title, page));
  return await response.json();
}

async function callApi() {
  let data = await callService('spiderman', 1);
  console.log(data.data.length);
}

callApi();

Upvotes: 0

axiac
axiac

Reputation: 72226

An async function always returns a Promise.

If you invoke sign() inside another function then you have to await for it and this requires making the caller function also an async function and so on and so forth.

Eventually, at the top-level code you have to use the regular .then().catch() syntax to wait for the Promise to settle:

sign()
    .then((result) => {
        // do something with the result (e.g. put it into the response header)
        console.log(result);
    })
    .catch((err) => {
        // something wrong happened and the Promise was rejected
        // handle the error
        console.log(`There was an error: ${err.message || err}`);
    });

Upvotes: 1

Guerric P
Guerric P

Reputation: 31815

You should not return the value of an async function as is, since it is a Promise

await for it before serializing it.

Upvotes: 3

Related Questions