javascript - Promise.all 的顺序执行

标签 javascript arrays node.js promise es6-promise

您好,我需要一个接一个地执行 promise ,如何使用 promise 实现这一点。所有帮助都会很棒。下面是我目前正在使用的代码示例,但它是并行执行的,因此搜索将无法正常工作

public testData: any = (req, res) => {
    // This method is called first via API and then promise is triggerd 
    var body = req.body;

    // set up data eg 2 is repeated twice so insert 2, 5 only once into DB
    // Assuming we cant control the data and also maybe 3 maybe inside the DB
    let arrayOfData = [1,2,3,2,4,5,5];

    const promises = arrayOfData.map(this.searchAndInsert.bind(this));

    Promise.all(promises)
        .then((results) => {
            // we only get here if ALL promises fulfill
            console.log('Success', results);
            res.status(200).json({ "status": 1, "message": "Success data" });
        })
        .catch((err) => {
            // Will catch failure of first failed promise
            console.log('Failed:', err);
            res.status(200).json({ "status": 0, "message": "Failed data" });
        });
}

public searchAndInsert: any = (data) => {
    // There are database operations happening here like searching for other
    // entries in the JSON and inserting to DB
    console.log('Searching and updating', data);
    return new Promise((resolve, reject) => {
        // This is not an other function its just written her to make code readable
        if(dataExistsInDB(data) == true){
            resolve(data);
        } else {
            // This is not an other function its just written her to make code readable
            insertIntoDB(data).then() => resolve(data);
        }
    });
}

我在谷歌中查找并看到 reduce 会有所帮助我将不胜感激任何关于如何将其转换为 reduce 或您建议的任何方法的帮助(.map 中的并发不起作用)

最佳答案

不幸的是,Promises 不允许对其流程进行任何控制。这意味着 -> 一旦你创建了新的 Promise,它将按照他们喜欢的方式执行它的异步部分。

Promise.all 不会更改它,它的唯一目的是检查您放入其中的所有 promise ,并在所有 promise 完成(或其中之一失败)后解决.

要能够创建和控制异步流程,最简单的方法是将 Promise 的创建包装到函数中并创建某种工厂方法。然后,无需预先创建所有 promise ,您只需在需要时只创建一个 promise ,等到它被解决,然后它继续以相同的行为。

async function doAllSequentually(fnPromiseArr) {
  for (let i=0; i < fnPromiseArr.length; i++) {
    const val = await fnPromiseArr[i]();
    console.log(val);
  }
}

function createFnPromise(val) {
  return () => new Promise(resolve => resolve(val));
}

const arr = [];
for (let j=0; j < 10; j++) {
  arr.push(createFnPromise(Math.random()));
}

doAllSequentually(arr).then(() => console.log('finished'));

PS:使用标准的 promise-chains 也可以不使用 async/await,但它需要用递归实现。

关于javascript - Promise.all 的顺序执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54867318/

相关文章:

javascript - 在 Google Maps api v3 中制作可拖动部分

javascript - GraphqlJS-类型冲突-无法使用联合或接口(interface)

javascript - Angular 2 : get the count of child components - when in the lifecycle and how

javascript - 动态下拉菜单 jQuery 内联错误

windows - Windows 上的 Node.js 和文件系统 - EBUSY 错误

javascript - 如何使用 jQuery 替换输入字段的特定值?

Java长度方法错误

javascript - 使用动态键对嵌套的对象数组进行排序

javascript - 使用 jasmine 单元测试框架对 node.js 进行单元测试

javascript - NodeJs - 如何在呈现的 EJS 中呈现 EJS?