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
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!