嵌套承诺会产生类似的效果

Nesting promises for a parallel effect?

本文关键字:承诺 嵌套      更新时间:2023-09-26

我不得不在承诺中嵌套一个承诺,这可以吗,还是被认为是糟糕的做法?

  1. 我有一个类,它有一个方法fetchArticlesfetchImagesmain
    • main是调用fetchArticles+fetchImages
    • fetchArticles从另一个文件中运行一个函数,该函数返回promise,但我也在fetchArticles类方法本身上返回promise。因此,当它获取文章时,它将继续获取图像
    • fetchImages方法未被承诺,而是从另一个文件中调用一个承诺的函数

我不确定这是否是实现鹦鹉学舌效果的最佳方式?

main () {
    // Call the promised fetchArticles class method
    this.fetchArticles()
    .then ( () => this.fetchImages( () => {
         this.res.json(this.articles.data);
    }));
}

fetchArticles () {
    return new Promise ((fullfil, rej) => {
      // Calling a promised function which simply returns an array of articles
      fetchArticles (this.parametersForApiCall)
       .then ( (data) => {
        this.articles.data = data;
        this.articles.imageIds = [1,5,2,8,99,1000,22,44,55,120,241]; // Extract image IDS and save to class this
        fullfil();
      })
      .catch ( (err) => {
        console.log ("Something went wrong with api call", err);
        res.json({error: "Something went wrong", code: 1011});
        reject();
      });
    });
  }
fetchImages (cb) {
      // Calling a promised function which simply returns an array of images
    fetchImages (this.imageIds).then( (imgs) => {
      this.images = imgs;
      cb (); // Temp callback method
    }).catch ( (err) => {
      console.log (err, "error finding images in then")
    })
  }
}

我应该使用异步并行之类的东西吗?注意,我在fetchImages方法中临时添加了一个callback,直到找到一个很好的链接承诺的解决方案。

几个注意事项:

  1. 您在fetchArticles函数中创建了一个不必要的承诺。您可以直接返回承诺的fetchArticles的结果。

  2. 使用Promise.all可以让你同时发射两个项目。如果你的两种方法不相互依赖,那么这是一个很好的方法。我已经用那个代码更新了main函数。

  3. 类似地,您可以直接在fetchImages函数中返回promise。因为这也是承诺的,所以您不再需要回调。我把它拿走了。

生成的代码

main () {
    // Call the promised fetchArticles and fetchImages class methods
    Promise.all([this.fetchArticles(), this.fetchImages()])
      .then(() => this.res.json(this.articles.data));
}

fetchArticles () {
  // Calling a promised function which simply returns an array of articles
  return fetchArticles (this.parametersForApiCall)
    .then ( (data) => {
      this.articles.data = data;
      this.articles.imageIds = [1,5,2,8,99,1000,22,44,55,120,241]; // Extract image IDS and save to class this
    })
    .catch ( (err) => {
      console.log ("Something went wrong with api call", err);
      res.json({error: "Something went wrong", code: 1011});
      reject();
    });
}
fetchImages () {
    // Calling a promised function which simply returns an array of images
    return fetchImages (this.imageIds).then( (imgs) => {
      this.images = imgs;
    }).catch ( (err) => {
      console.log (err, "error finding images in then")
    })
  }
}

似乎是Promise.all的工作。