简体   繁体   中英

javascript forEach on array inside promise

In my javascript function, I am able to call a rest service inside a promise.

function update(item) {
  return new Promise(function (resolve, reject) {
    client.get(urls[env] + item['itemId'], function (data, response) {
        try {......

Now, when I modify same function to handle item array as:

function update(itemList) {
  return new Promise(function (resolve, reject) {
    itemList.forEach((item) =>{
        client.get(urls[env] + item['itemId'], function (data, response) {
            try {

This doesn't work. Rest call just doesn't happen. It neither fails.

What am I missing here?

You could try to write a function that would return a promise for client.get instead of a callback.

The following code shows how to do this, I am using ES5 but assuming native Promises or a polyfill:

function promiseClientGet(o, url){
  return new Promise(function(resolve,reject){
    o.get(url, function (data, response) {
      // try {...... need to call resolve or reject
    });
  });
}

function update(itemList) {
  return Promise.all(itemList.map(function(item) {
    return promiseClientGet(urls[env] + item['itemId'], client);
  }))
}

Using ES6:

const promiseClientGet = (o, url) => new Promise((resolve,reject)=> {
  o.get.apply(o, (data, response) => {
    // try {...... need to call resolve or reject
  });
});

const update = itemList =>
  Promise.all(itemList.map(item => promiseClientGet(urls[env] + item['itemId'], client)));

If you just want to make parallel requests and wait for all of them to finish and return the results than you can use Promise.all()

const getAll = (items) =>
    Promise.all(items.map(i => callApi(i)))

getAll([1, 2, 3])
    .then(results => console.log(results))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM