簡體   English   中英

我應該在每個類方法中創建一個新的Promise嗎?

[英]Should I create a new Promise in each class method?

我想在我的類方法中使用Promises。 Promise反模式中,我讀到為每個新函數創建一個新的承諾被認為是壞的。

但是,我不想在我的項目中返回不相關的promise,所以我想做這樣的事情:

class MyClass {

  async getToken() {
    return new Promise(
      (resolve, reject) => {
        // . . .
        const token_str = '<response_from_http_request>';
        resolve(token_str);
      }
    )
  }

  async doSomething(token) {
    return new Promise(
      (resolve, reject) => {
        const result = // . . .
        resolve(result);
      }
    )
  }

  async doAnotherSomething(token) {
    return new Promise(
      (resolve, reject) => {
        const result = // . . .
        resolve(result);
      }
    )
  }

}

然后我會像這樣使用它:

let instance = new MyClass();

(async () => {
    const token = await instance.getToken();

    const result1 = await instance.doSomething(token);
    console.log(result1);

    const result2 = await instance.doAnotherSomething(token);
    console.log(result2);

})();

這看起來像是一種有效的方法嗎,或者這也是一個反模式? 如果是這樣,我怎么能避免編寫這樣的代碼?


編輯:如果我需要進行幾個連續的http調用,對結果執行一些操作然后返回基於它的Promise怎么辦?

我理解的方式,如果我不做一個新的 Promise,我必須返回由got.js庫創建的,包括http響應數據。

相反,我想返回一個包含我的類方法結果的Promise。

例:
  async getCityWeather( city_name ) { return new Promise( (resolve, reject) => { // get the city id based on its name const city_id = await got(`https://my-api/getCityIdByName/${city_name}`); // now get the weather info for the city with id `cityid` const weather_info = await got(`https://my-api/weatherById/${city_id}`); // make an object to return const temperature = { weather_info.temp_min, weather_info.temp_max, } resolve(temperature); // ... all error handling are omitted } ) } 

我不想返回包含got.js返回值的Promise,我想根據http請求調用返回我的值。

async函數總是返回一個Promise

在以下情況下,函數/方法將返回Promise:

  • 你明確地創建並從它的身體返回了一個Promise。
  • 您返回了一個存在於方法之外的Promise。
  • 您將其標記為async

因為您可以await Promise和instance.doSomething已經是異步標記的方法,您可以等待它而無需顯式返回Promise。

只需return它的結果,就像在常規同步方法中一樣。

我不想在我的項目中返回不相關的承諾......

除非您實際上在方法中執行異步操作(訪問文件系統,數據庫調用,計時器等...), 否則不需要將其包裝在Promise ,也不需要在需要結果時await它。

實際上需要在Promise包裝內容的最常見情況是,如果你有一個使用回調函數的異步函數,但你想將它用作Promise

 // plain old callback-style asynchronous functions: const getFooViaCallback = callback => { setTimeout(() => { callback('foo') }, 150) } const getBarViaCallback = callback => { setTimeout(() => { callback('bar') }, 150) } class Foo { constructor() {} getFooViaPromise() { // wrap callback-style code in a Promise // so we can await it. return new Promise(resolve => { getFooViaCallback(result => { resolve(result) }) }) } getBarViaPromise() { // wrap callback-style code in a Promise // so we can await it. return new Promise(resolve => { getBarViaCallback(result => { resolve(result) }) }) } getBaz() { // no reason to wrap this in a Promise, // since it's a synchronous method. return 'baz' } async getFooBarBaz() { const foo = await this.getFooViaPromise() const bar = await this.getBarViaPromise() const baz = this.getBaz() return foo + ',' + bar + ',' + baz } } ;(async() => { const foo = new Foo() const result = await foo.getFooBarBaz() console.log('foo.getFooBarBaz() result: ', result) })() 

為簡潔起見,我在上面的代碼段中省略了錯誤處理,但你應該使用throw in async -marked方法來引發錯誤。 這相當於在Promise中調用.reject()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM