从调用代码中抽象出异步/等待细节

问题描述 投票:0回答:1

我正在编写 JavaScript 来从 API 加载信息。

我写了以下代码:

export class Api {

    async #apiGet(endpoint) {
        const response = await fetch('/api/' + endpoint);
        return await response.json()
    }
    
    loadSavedItems() {
        const endpoint = 'saved-items/'
        return this.#apiGet(endpoint)
    }
}

我想做的是同步调用

loadSavedItems
,而不必使用
await
关键字。我希望所有有关等待/异步/承诺的知识都保留在 API 类中,而不是泄漏到调用代码中。

但是,在调用代码时我发现我仍然需要使用

await
才能获取信息。例如:

const api = new Api()

// this returns a Promise{<pending>} - I want it to just return a list of saved items
const savedItems = api.loadSavedItems()

// in order to get the list of saved items I have to use `await`
// which means this either has to be inside an async function or in the top level of a module
const actualSavedItems = await api.loadSavedItems()

有没有办法从调用代码中抽象出 async/await ?这可能吗?

javascript async-await
1个回答
0
投票

Javascript 没有提供直接的方法来抽象异步/等待。但你仍然可以在代码中做一些修改,以尽量减少 async/await 的暴露。你可以使用回调或事件监听器来达到目标。

export class Api {

    async #apiGet(endpoint) {
        const response = await fetch('/api/' + endpoint);
        return await response.json()
    }
    
    loadSavedItems() {
        const endpoint = 'saved-items/'
       this.#apiGet(endpoint)
.then(data=>callback(data))
    .catch(error)
    }
}

你可以这样称呼它 ->

const api = new Api();

api.loadSavedItems(savedItems => {
    
    console.log(savedItems);
});
© www.soinside.com 2019 - 2024. All rights reserved.