扫码关注官方订阅号
欢迎选择我的课程,让我们一起见证您的进步~~
疑惑1
修正:
promise .then(A) .then(B) .then(function(state){ if(state){ return C1.then(C2); } return C; }) .then(D);
好像也不算帅,期待更屌的实现
疑惑2
如果发生在循环里,譬如:对一个数组进行遍历,对每一元素处理的结果都是一个Promise,可以这样写:
Promise
var userIds = ['aaa', 'bbb', 'ccc']; //这里getUserById返回的是Promise var promises = arr.map(userIds => getUserById(userId)); Promise .all(promises) .then(function(users) { console.log(users); //这里就是users的列表了 });
疑问1可以这样
promise.then(A).then(B).then(function () { if (state) {//state可以来自B或A return C(); } else { return C1().then(C2); } }).then(D);
疑问2,如果循环需要并行用Promise.all
let functions = [...] let promises = function.map((fn) => fn()); Promise.all(promises).then((results) => console.log(results))
如果要串行就这样
let functions = [...] let promise = funcitons.reduce(function (now, fn) { reutrn now.then(fn); }, Promise.resolve()); promise.then((result) => console.log(result));
推荐es7的async/await用同步方式写异步代码
微信扫码关注PHP中文网服务号
QQ扫码加入技术交流群
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
PHP学习
技术支持
返回顶部
疑惑1
修正:
疑惑2
如果发生在循环里,譬如:对一个数组进行遍历,对每一元素处理的结果都是一个
Promise,可以这样写:疑问1可以这样
疑问2,如果循环需要并行用Promise.all
如果要串行就这样
推荐es7的async/await
用同步方式写异步代码