Promise.all的顺序执行

Aks*_*pal 7 javascript arrays node.js promise es6-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);
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

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

lib*_*bik 12

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

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

为了能够创建和控制异步流程,最简单的方法是将 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'));
Run Code Online (Sandbox Code Playgroud)

PS:使用标准 Promise 链也可以不使用 async/await,但需要使用递归来实现。