gpt4 book ai didi

javascript - 如何检查 Javascript Promise 是否已经实现?

转载 作者:行者123 更新时间:2023-11-29 17:47:13 25 4
gpt4 key购买 nike

我修改了这个example通过添加循环和 Deferred 对象来了解所有的 promise 都已实现。

我想做的是将所有的 promise 放入一个数组中,并在所有 promise 都实现时打印出来。

这是我的代码:

get_data();

function get_data() {


var myPromise = [];
var calls = [];
var resultset = '';
for (var j = 0, k = 5; j < k; j++) {
var d = $.Deferred();
var p = get_result();
if (p.isPending()) {
console.log('pending');
}
p.then(function(resultset) {
if (p.isFulfilled()) {
myPromise.push(resultset);
calls.push(d);
}
});

}

$.when.apply($, calls).then(function() {
console.log(myPromise); // always prints an empty array.
});
}

function get_result() {

return MakeQuerablePromise(new Promise(function(result, reject) {
setTimeout(function() {
result("Yeah !");
}, 10000);
}));
}

Fiddle完整代码

最佳答案

来自 MDN :

The Promise.all(iterable) method returns a single Promise that resolves when all of the promises in the iterable argument have resolved or when the iterable argument contains no promises. It rejects with the reason of the first promise that rejects.

var p1 = Promise.resolve(3);
var p2 = 1337;
var p3 = new Promise((resolve, reject) => {
setTimeout(resolve, 100, 'foo');
});

Promise.all([p1, p2, p3]).then(values => {
console.log(values); // [3, 1337, "foo"]
});

关于javascript - 如何检查 Javascript Promise 是否已经实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48144079/

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