gpt4 book ai didi

javascript - 一组 promise 是否仅在传递给所有 promise 后才开始执行?

转载 作者:行者123 更新时间:2023-11-30 15:02:11 26 4
gpt4 key购买 nike

如果构建了一个 promise 数组,然后将其传递给 Promise.all,是立即开始执行还是仅在调用 Promise.all 后开始执行?

示例代码:

let promises: Promise<string> [] = [this.methodCall(), this.methodCall(), this.methodCall()];

Promise.all(promises).then(values => {
...
}).catch(error => {
...
});

此外,此代码示例是否会捕获所有拒绝?

最佳答案

Promise 创建时,它会立即开始工作。查看日志。 Promise body 函数起作用,然后在 5 秒后启动 Promise.all

const pr = new Promise((resolve, reject) => {
console.log('Started !!!');
resolve();
});

console.log('Before setTimeout');

setTimeout( () => {
Promise.all([pr]).then(result => console.log('Resolved !!!'));
}, 5000)

console.log('After setTimeout');

来自Documentation

A function that is passed with the arguments resolve and reject. The executor function is executed immediately by the Promise implementation, passing resolve and reject functions (the executor is called before the Promise constructor even returns the created object).

关于javascript - 一组 promise 是否仅在传递给所有 promise 后才开始执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46348132/

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