如何使用承诺流式传输数据?

How to stream data using promises?

如何使用 promises 流式传输数据。

我在两个不同的文件中有两个不同的函数。其中一个调用 API 服务,而 returns 一个承诺。

  async myPromise(){
    return new Promise((resolve, reject) => {
      callToAnAPI().then(()=>{
          resolve ("pending");
      }).then(()=>{
        resolve(callToAnotherAPI());
      })
      .catch(err=>{
          // error handling
      });
    });
  }

在另一个文件中我有这样一个函数:

  async myPromise2(){
    functionFromOtherFile().then((data)=>{
        // how can I get 'pending' here?
    }).then(data =>{
        // how can I get data fromncallToAnotherAPI() here?
    })
  }

我想知道 api 已被调用并且处于 'pending' 状态。我怎样才能做到这一点?

Stream 只是一个异步迭代器...所以我们可以只使用回调,就像 node.js

function myPromise(cl) {
    cl(null, "pending")
    setTimeout(() => {
        cl(null, "data")
    }, 2000);
}

function myPromise2() {
    myPromise((err, data) => {
        console.log(data)
    })
}

myPromise2()

我认为最优雅的方法是 return 两个 promise 并分别处理它们。

  function myPromise(){
    const api1Status = callToAnAPI().then(()=>{
        resolve ("pending");
    });
    return [
      api1status,
      api1status.then(()=>{
        resolve(callToAnotherAPI());
      })
      .catch(err=>{
          // error handling
      })
    ];
  }

那么第二个文件会这样使用它:

  async myPromise2(){
    const [api1, api2] = functionFromOtherFile();
    const shouldSayPending = await api1;
    const shoudHaveData = await api2;
  }

第一个函数不需要是异步函数,你只需return一些承诺。

您还可以考虑使用异步生成器,它会在第一种方法中为您提供更好的代码,但在第二种方法中则不太好,如下所示:

async function* myPromise() {
    try {
        yield await callToAnApi(); // we need to await here so that 
        yield callToAnotherApi();  // this method is executed after.
    } catch(e) {
        // error handling
    }

}

对方会出现这样的结果:

async myPromise2() {
    const progress = theIteratorFromOtherFile(); // just call the function*

    const shouldBePending = (await progress.next()).value;
    const theOtherResult = (await progress.next()).value;
}

就性能而言,两者之间几乎没有区别 - 您正在进行异步操作,因此这些是您的瓶颈。然后选择取决于您的个人喜好。