gpt4 book ai didi

javascript - 如何知道何时在动态 "iterable"参数中解决所有 Promises?

转载 作者:可可西里 更新时间:2023-11-01 02:36:51 25 4
gpt4 key购买 nike

我的问题是我不知道如何知道动态 promise 数组何时解决了所有 promise 。

举个例子:

var promiseArray = [];
promiseArray.push(new Promise(){/*blablabla*/});
promiseArray.push(new Promise(){/*blablabla*/});
Promise.all(promiseArray).then(function(){
// This will be executen when those 2 promises are solved.
});
promiseArray.push(new Promise(){/*blablabla*/});

我这里有个问题。 Promise.all 行为将在解决前两个 promise 时执行,但是,在解决这两个 promise 之前,将添加第三个 promise ,并且不会考虑这个新 promise 。

所以,我需要的是这样说:“嘿 Promise.all,你有一个动态数组要检查”。我该怎么做?

请记住,这只是一个示例。我知道我可以将行 Promise.all 移动到最后一行,但实际上新的 promise 是在解决另一个 promise 时动态添加的,并且新的 promise 也可以添加新的 promise ,所以,它是一个真正的动态数组。

我的真实用例是这样的:

  1. 我使用 Twitter API 检查是否有新推文(使用 Search Api)。
  2. 如果我发现新的推文,我会将其添加到 MongoDB(这里我们有 Promises)。
  3. 如果这些新推文与我的 MongoDB 中没有的用户相关(这里我们有新的 promise ,因为我必须去 MongoDB 检查我是否有那个用户),我们去 Twitter API获取用户信息(更多 promise ),我们将这些新用户添加到 MongoDB(是的,更多 promise )。
  4. 然后,我转到 MongoDB 插入新值以将新推文与这些新用户相关联(更多 promise !wiii!)。
  5. 当对 MongoDB 的所有查询都已解决(所有选择、更新、插入)时,关闭 MongoDB 连接。

另一个困难的例子:

var allPromises = [];

allPromises.push(new Promise(function(done, fail){
mongoDB.connect(function(error){
//Because mongoDB works with callbacks instead of promises
if(error)
fail();
else
ajax.get('/whatever').then(function(){
if (somethingHappens) {
allPromises.push(new Promise(function(done, fail){ //This promise never will be take in account
// bla bla bla
if (somethingHappens) {
allPromises.push(new Promise(function(done, fail){ //This promise never will be take in account
// bla bla bla
}));
} else {
ajax.get('/whatever/2').then(function(){
if (somethingHappens) {
allPromises.push(new Promise(function(done, fail){ //This promise never will be take in account
// bla bla bla
}));
}
});
}
}));
} else {
ajax.get('/whatever/2').then(function(){
if (somethingHappens) {
allPromises.push(new Promise(function(done, fail){ //This promise never will be take in account
// bla bla bla
if (somethingHappens) {
allPromises.push(new Promise(function(done, fail){ //This promise never will be take in account
// bla bla bla
}));
} else {
ajax.get('/whatever/2').then(function(){
if (somethingHappens) {
allPromises.push(new Promise(function(done, fail){ //This promise never will be take in account
// bla bla bla
}));
}
});
}
}));
}
});
}
});
});
}));

Promise.all(allPromises).then(function(){
// Soooo, all work is done!
mongodb.close()!
});

那么,现在,一个美丽的例子。当调用最后一个(我们不知道哪个是最后一个)promise 时,我们需要调用 showAllTheInformation 函数。你是怎么做到的?:

var name = 'anonimus';
var date = 'we do not know';

function userClikOnLogIn() {
$http.get('/login/user/password').then(function(data){
if (data.logguedOk) {
$http.get('/checkIfIsAdmin').then(function(data){
if (data.yesHeIsAnAdmin) {
$http.get('/getTheNameOfTheUser').then(function(data){
if(data.userHasName) {
$http.get('/getCurrentDate').then(function(data){
currentDate = data.theNewCurrentDate;
});
}
});
}
});
}
});
}

function showAllTheInformation() {
alert('Hi ' + name + ' today is:' + date);
}

这里是另一个有更多上下文的例子: https://jsfiddle.net/f0a1s79o/2/

最佳答案

您可以编写一个简洁的小递归函数来包装 Promise.all 以处理对原始 promise 的添加:

/**
* Returns a Promise that resolves to an array of inputs, like Promise.all.
*
* If additional unresolved promises are added to the passed-in iterable or
* array, the returned Promise will additionally wait for those, as long as
* they are added before the final promise in the iterable can resolve.
*/
function iterablePromise(iterable) {
return Promise.all(iterable).then(function(resolvedIterable) {
if (iterable.length != resolvedIterable.length) {
// The list of promises or values changed. Return a new Promise.
// The original promise won't resolve until the new one does.
return iterablePromise(iterable);
}
// The list of promises or values stayed the same.
// Return results immediately.
return resolvedIterable;
});
}

/* Test harness below */

function timeoutPromise(string, timeoutMs) {
console.log("Promise created: " + string + " - " + timeoutMs + "ms");
return new Promise(function(resolve, reject) {
window.setTimeout(function() {
console.log("Promise resolved: " + string + " - " + timeoutMs + "ms");
resolve();
}, timeoutMs);
});
}

var list = [timeoutPromise('original', 1000)];
timeoutPromise('list adder', 200).then(function() {
list.push(timeoutPromise('newly created promise', 2000));
});
iterablePromise(list).then(function() { console.log("All done!"); });

在带有 lambda 且没有注释的 ES6 中,这可以更短:

function iterablePromise(iterable) {
return Promise.all(iterable).then((resolvedIterable) => {
if (iterable.length != resolvedIterable.length) {
return iterablePromise(iterable);
}
return resolvedIterable;
});
}

或者,作为 Radstheir answer 中用 async/await 表示,但作为函数:

async function iterablePromise(iterable) {
let resolvedIterable = [];
while (iterable.length !== resolvedIterable.length) {
resolvedIterable = await Promise.all(iterable); // implicit "then"
}
return resolvedIterable;
}

请记住,这只涉及添加,而且它仍然有点危险:您需要确保回调顺序是这样的,即任何正在运行的 promise 都会在 Promises.all 之前将自己添加到列表中可以调用回调。

关于javascript - 如何知道何时在动态 "iterable"参数中解决所有 Promises?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37801654/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com