最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

我应该建立在每类中的方法一个新的承诺?

运维笔记admin14浏览0评论

我应该建立在每类中的方法一个新的承诺?

我应该建立在每类中的方法一个新的承诺?

我想利用我的类方法的承诺。在Promise antipatterns我读了创建为每个新功能的新的承诺被认为是不好的。

不过,我不希望在我的项目返回不相关的承诺,所以我认为做这样的事情的:

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调用后,对结果有一定的操作,然后返回基于它的承诺是什么?

我明白,如果我不做出新的承诺的方式,我不得不返回由got.js库,其中包括HTTP响应数据做出的一个。

相反,我想返回包含我的类方法的结果的承诺。

Example:
  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返回值,我想基于HTTP请求调用返回我的价值的承诺。

回答如下:

async函数总是返回Promise

函数/方法会返回一个承诺在下列情况下:

  • 您明确地创建并返回从它的身体的承诺。
  • 您返回存在的法外的承诺。
  • 您将其标记为async

既然你可以await一个承诺,instance.doSomething已经是一个异步标记的方法,你可以等待它,而无需显式地返回的承诺。

只要return它的成绩,就像您在常规同步方法。

我不想在我的项目返回不相关的承诺...

除非你真的做一些异步在你的方法(访问文件系统,数据库调用,定时器等),你不需要包装在一个Promise,也不是当你需要一个结果await它。

在那里你实际上需要在Promise包裹的东西,最常见的情况是,如果你有一个工程,并使用callbacks异步函数,但是你想使用它作为一个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)
})()
发布评论

评论列表(0)

  1. 暂无评论