【发布时间】:2021-09-09 05:51:54
【问题描述】:
在 JavaScript 中,我调用了一个返回 id 的 promise;我们称之为promise1。 promise1 有一个跟随 .then(),给定从 promise1 返回的 id,它调用一个 for-each 循环。在此循环的每次迭代中,都会执行promise2
promsie2 也有一个.then()。这样promise2返回的数据就可以使用了。
mycode.js
exports.my_function = (req, res) => {
var data = req.body;
var name_array = ["Jeff", "Sophie", "Kristen"]
var personal_ID_arr = []
promise1.getID(data) //promise1 gets an int 'id'
.then(id => {
array.forEach(name => { //for each name
promise2.getPersonalID(name, id) //promise2 creates a personal id for each person using their name and the id generated from promise1
.then(personalID => {
personal_ID_arr.push(personalID) //add the generated personal id to an arr
})
})
})
//will need to operate on 'personal_ID_arr' here after the above finishes or possibly still within the promise1's .then; as long as the arr is filled fully
}
但是,我遇到了同步性问题,不允许这种类型的逻辑发生,因为一旦进入程序的循环方面,事情就会开始无序发生。在执行这些承诺后,我还需要使用填写的“personal_ID_arr”执行另一个功能
我已经查看了有关 Promise 链接的其他问题,但这是一个不同的情况,因为 for 循环需要处理来自第一个 Promise 的数据并在 .then() 中使用 .then()。当然,如果存在更好的结构,我不需要保留这种结构。
任何帮助将不胜感激
【问题讨论】:
-
我不是 100% 清楚你想要达到的目标,但听起来你想在这里使用Promise.all。
标签: javascript asynchronous promise synchronization es6-promise