如何在JS中使`return`尊重异步/等待?

时间:2018-07-05 10:28:28

标签: javascript async-await

我正在尝试使此代码(类方法)返回String

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

问题是它忽略await并返回Promise。此函数的返回值用作HTTP请求标头,而npmlog则说它是

apisign: Promise { 'faaa3f1409977cbcd4ac50b5f7cd81ec' }

在Wireshark捕获的网络流量中,我看到

apisign: [object Promise]

如何使return尊重await,或者应该怎么写才能使它返回String

3 个答案:

答案 0 :(得分:2)

您不应该按原样返回async function的值,因为它是Promise

await,然后对其进行序列化。

答案 1 :(得分:0)

一个async function总是returns a Promise

如果您在另一个函数中调用sign(),则必须为此await,这要求将调用者函数也变为async函数,依此类推。

最终,在顶层代码中,您必须使用常规的.then().catch()语法来等待Promise解决:

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

答案 2 :(得分:0)

您将必须awaitasync函数的响应。

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