0

can you please tell me how to print response of async operation in sync in javascript ?

I have 3 promises which called asynchronously but want to fetch data synchronously I know Promise.all but it fail when any one of promise fail .I need it show those promises which are resolved. Secondly asyn await but block the async request .

so it there any other way to do mean we fire multiple request asynchronously and fetch data synchronously print all resolved promises .

I tried like this

// Import stylesheets
import './style.css';

// Write Javascript code!
let promises =[]
const appDiv = document.getElementById('app');
appDiv.innerHTML = `<h1>JS Starter</h1>`;
var promise1 = new Promise(function(resolve, reject) {
  setTimeout(resolve, 1000, 'foo');
});

var promise2 = new Promise(function(resolve, reject) {
  setTimeout(resolve, 2000, '222foo');
});

var promise3 = new Promise(function(resolve, reject) {
  setTimeout(reject, 2000, 'reject');
});

// Promise.all([promise1,promise2]).then((result)=>{
//  appDiv.innerHTML ='a::' +result[0] + 'b::'+result[1]
// }).catch(reason => { 
//   console.log(reason)
//   appDiv.innerHTML =reason
// });
promises.push(promise1);
promises.push(promise2);
promises.push(promise3);
Promise.all(promises.map((promise, i) =>
    promise.catch(err => {
        throw err;
    })
)).then(results => {
    console.log("everything worked fine, I got ", results);
}, err => {
    console.error("promise No  failed with ", err);
});

https://stackblitz.com/edit/js-l1cfac

any update

naveen
  • 867
  • 4
  • 18
  • 42

0 Answers0