Wait until all promises complete even if some rejected

前端 未结 18 1912
醉酒成梦
醉酒成梦 2020-11-21 04:55

Let\'s say I have a set of Promises that are making network requests, of which one will fail:

// http://does-not-exist will throw a TypeError
va         


        
18条回答
  •  南方客
    南方客 (楼主)
    2020-11-21 05:46

    You can execute your logic sequentially via synchronous executor nsynjs. It will pause on each promise, wait for resolution/rejection, and either assign resolve's result to data property, or throw an exception (for handling that you will need try/catch block). Here is an example:

    function synchronousCode() {
        function myFetch(url) {
            try {
                return window.fetch(url).data;
            }
            catch (e) {
                return {status: 'failed:'+e};
            };
        };
        var arr=[
            myFetch("https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"),
            myFetch("https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/NONEXISTANT.js"),
            myFetch("https://ajax.NONEXISTANT123.com/ajax/libs/jquery/2.0.0/NONEXISTANT.js")
        ];
        
        console.log('array is ready:',arr[0].status,arr[1].status,arr[2].status);
    };
    
    nsynjs.run(synchronousCode,{},function(){
        console.log('done');
    });

提交回复
热议问题