javascript - 将 forEach() 与 promise 一起使用,同时在 .then() 链中访问先前的 promise 结果?

标签 javascript scope ecmascript-6 promise es6-promise

我有以下 promise 的功能:

const ajaxRequest = (url) => {
  return new Promise(function(resolve, reject) {
    axios.get(url)
      .then((response) => {
        //console.log(response);
        resolve(response);
      })
      .catch((error) => {
        //console.log(error);
        reject();
      });
  });
}


const xmlParser = (xml) => {
  let { data } = xml;
  return new Promise(function(resolve, reject) {
    let parser = new DOMParser();
    let xmlDoc = parser.parseFromString(data,"text/xml");

    if (xmlDoc.getElementsByTagName("AdTitle").length > 0) {
      let string = xmlDoc.getElementsByTagName("AdTitle")[0].childNodes[0].nodeValue;
      resolve(string);
    } else {
      reject();
    }
  });
}

我正在尝试为 JSON 数组中的每个对象应用这些函数:

const array = [{"id": 1, "url": "www.link1.com"}, {"id": 1, "url": "www.link2.com"}]

我想出了以下解决方案:

function example() {
    _.forEach(array, function(value) {
        ajaxRequest(value.url)
            .then(response => {
                xmlParser(response)
            .catch(err => {
                console.log(err);
            });
        });
    }
 }

我想知道这个解决方案是否可以接受两件事:

  1. 在以下事项中对 promises 应用 forEach() 是一种好的做法吗?

  2. 是否有更好的方法将先前的 promise 结果作为参数传递到 then() 链中? (我正在传递 response 参数)。

最佳答案

您可以使用 .reduce() 访问之前的 Promise

function example() {
    return array.reduce((promise, value) =>
       // `prev` is either initial `Promise` value or previous `Promise` value
       promise.then(prev => 
         ajaxRequest(value.url).then(response => xmlParser(response))
       )
    , Promise.resolve())
 }
 // though note, no value is passed to `reject()` at `Promise` constructor calls
 example().catch(err => console.log(err)); 

注意,在 ajaxRequest 函数中不需要 Promise 构造函数。

const ajaxRequest = (url) => 
    axios.get(url)
      .then((response) => {
        //console.log(response);
        return response;
      })
      .catch((error) => {
        //console.log(error);
      });

关于javascript - 将 forEach() 与 promise 一起使用,同时在 .then() 链中访问先前的 promise 结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45296475/

相关文章:

javascript - 当需要从类中回调时,将 React 常量移至其自己的文件中

javascript - 当我不期望时变得不确定

python - 如何修改另一个作用域的变量?

c++ - C++ 是否擅长为局部变量重用堆栈内存?

javascript - Eslint:如何处理依赖函数的 no-use-before-define?

javascript - 如何发布表中的一行内容,该表是服务器 GET 请求的响应?

C++ stoi 超出范围问题

javascript - 如何在测试之间重置 Redux?

javascript - Laravel + Ajax - 如何通过 GET 中的查询字符串查询项目

javascript - 如何从 destination-out 中删除剩菜?