如何 return 从异步代码块中承诺

how to return promise from an async code block

我想发送一个 http 请求和 return 使用打字稿的结果,在发送 http 请求之前,我想从 google chrome 本地存储中获取令牌并放入将令牌放入 http header。这是我的打字稿代码:

api_post:<T>(url: string, data: any): Promise<T> => {
    chrome.storage.local.get("token", function (result:any) {
        return fetch(url, {
            method: 'POST',
            headers: {
                'Content-type': 'application/json',
                'x-access-token': result,
            },
            body: JSON.stringify(data),
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error(response.statusText);
                }
                return response.json() as Promise<T>;
            });
    });  
},

问题是来自异步代码块内部的承诺 return,此函数显示错误:

interface Promise<T>
Represents the completion of an asynchronous operation

A function whose declared type is neither 'void' nor 'any' must return a value.ts(2355)

我应该如何处理 return chrome 本地存储中的承诺并使代码正常工作?

对于 follow-up 我的评论,你可以这样做:

api_post: async (url: string, data: any): Promise<T> => {
    const { result } = await chrome.storage.local.get("token");
    const response = await fetch(url, {
            method: 'POST',
            headers: {
                'Content-type': 'application/json',
                'x-access-token': result,
            },
            body: JSON.stringify(data),
        });
    return response;
},

注意: 这只是为了让您了解如何使用 async/await 重构您的方法。此代码可能需要一些调整。

我会使用 Promise constructor。然后,在链中解决最终期望值,并拒绝任何错误。

const api_post = <T>(url: string, data: any): Promise<T> => {
    return new Promise((resolve, reject) => {
        chrome.storage.local.get("token", function (result: any) {
            return fetch(url, {
                method: "POST",
                headers: {
                    "Content-type": "application/json",
                    "x-access-token": result,
                },
                body: JSON.stringify(data),
            }).then((response) => {
                if (!response.ok) {
                    reject(new Error(response.statusText));
                    return;
                }
                resolve(response.json() as Promise<T>);
            });
        });
    });
};

只是抛出另一个片段,因为 OP 似乎不喜欢 and I don't like the new Promise antipattern from

中的 async/await
const api_post = <T>(url: string, data: any): Promise<T> => {
  return chrome.storage.local.get("token")
    .then((result: any) => fetch(url, {
      method: "POST",
      headers: {
        "Content-type": "application/json",
        "x-access-token": result,
      },
      body: JSON.stringify(data),
    }))
    .then((response) => {
      if (!response.ok) {
        throw new Error(response.statusText);
      }
      return response.json();
    });
};