Javascript条件使用await of not

Yad*_*ada 0 javascript asynchronous

有没有办法可以编写这段代码,而无需调用 axios 的所有重复代码?

export const handler = async (event, useAwait) => {
  const { path, data } = JSON.parse(event);

  if (useAwait) {
    return await axios(`https://example.com/api${path}`, {
      method: 'post',
      headers: {
        'api-key': key,
      },
      data: data,
    });
  } else {
    // non-blocking
    axios(`https://example.com/api${path}`, {
      method: 'post',
      headers: {
        'api-key': key,
      },
      data: data,
    });
    return true;
  }
};
Run Code Online (Sandbox Code Playgroud)

Cer*_*nce 6

将 Promise 放入变量中,然后您可以有条件地返回它。

export const handler = async (event, useAwait) => {
    const { data } = JSON.parse(event);
    const prom = axios(`https://example.com/api${url}`, {
        method: 'post',
        headers: {
            'api-key': key,
        },
        data: data,
    });
    return useAwait ? (await prom) : true;
};
Run Code Online (Sandbox Code Playgroud)

也就是说,您也可以返回 Promise 本身 -await立即返回的内容没有帮助,因为您没有立即进入try.

return useAwait ? prom : true;
Run Code Online (Sandbox Code Playgroud)

但是调用这个函数而不返回结果看起来是一个坏主意,因为这样你可能会得到未处理的拒绝。在这种情况下,您可能希望.catch在 Promise 中添加 a 以避免这种情况。