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 聚类分析或者python进行数据分析
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号