weixin_33696822 2015-11-07 21:32 采纳率: 0%
浏览 92

如何在node.js中使用$ .when? [重复]

This question already has answers here:
                </div>
            </div>
                    <div class="grid--cell mb0 mt4">
                        <a href="/questions/21564993/native-support-for-promises-in-node-js" dir="ltr">Native Support for Promises in Node.js</a>
                            <span class="question-originals-answer-count">
                                (8 answers)
                            </span>
                    </div>
            <div class="grid--cell mb0 mt8">Closed <span title="2015-11-07 21:47:51Z" class="relativetime">4 years ago</span>.</div>
        </div>
    </aside>

I want to send a dynamic amount ajax requests at same time and want a callback to them all (i.e. the callback to the last one returning), but I am using node.js. I found a jquery version to solve it here Pass in an array of Deferreds to $.when() but how can I do this in node.js?

Thanks

</div>
  • 写回答

2条回答 默认 最新

  • weixin_33721427 2015-11-07 21:36
    关注

    Promise.all takes an array of promises and returns a Promise of Array. The node-fetch module can be used to make HTTP requests asynchronously (AJAX only really refers to browser-executed requests.)

    Bluebird is a nodejs Promise polyfill.

    Something like

    var fetch = require('node-fetch'),
        Promise = require('bluebird');
    
    function fetchUrls(URLs) {
        return Promise.all(URLs.map(function (URL) {
            return fetch(URL).then(function (response) {
                return response.json();
            });
        }));
    }
    
    fetchUrls(['url1','url2']).then(function (data) {
        // do stuff with the result data here
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀