Javascript:对象数组,异步更改每个对象中的值

Javascript: Array of objects, changing value in each object asynchronously

所以,我知道之前有人问过这个问题,我也尝试过其他答案,例如 .map(function(post){ async })(value),但我仍然卡住了...

所以,我有一个对象数组和一个 for 循环:

var postsData = [{thumbnail: www.website.com/image.jpg}, {thumbnail: www.website.com/image.jpg}, {thumbnail... etc}];

for (let i = 0; i < 3; i++) {
  let thumbnail = postsData[i].thumbnail;
  Cloudinary.uploader.upload(thumbnail, function(result){
    // not sure what to do here
    // result comes back as an object, and I want to change each thumbnail in
    // the postsData array to be result.public_id
  }, {transformation:[{}]});
} // go through all the items in the array

// do something with "updated" postsData array

一个例子会很有帮助,很明显,改变值涉及一些异步函数。

将数组中对象的 "thumbnail" 属性 设置为 result.public_id。创建一个函数,其中预期参数是 postsData 数组中的当前对象,通过将函数引用传递给 upload 函数来设置对象的 "thumbnail" 属性,传递数组 [=16] 的当前对象=] 对象利用 Function.prototype.bind()

var len = postsData.length;
var n = 0;

function handleData(result, prop) {
  prop["thumbnail"] = result_public.id;
  if (++n === len) complete(postsData);
}

function complete(data) {
  console.log(data, postsData);
}

for (let prop of postsData) {
  Cloudinary.uploader.upload(
    thumbnail
    , handleData.bind(null, prop)
    , {transformation:[{}]}
  );
}

plnkrhttp://plnkr.co/edit/SSyUG03pyAwXMVpHdGnc?p=preview

据我了解,您正在尝试遍历一个数组并对其每个元素执行异步函数。我要做的是使用 Promise.js(参见 enter link description here)。所以代码看起来像这样:

// create an array for the promises
const PromiseArr = [];
postsData.map(d => {
  PromiseArr.push(
    // do async actions and push them to array
    new Promise((resolve, reject) => {
       Cloudinary.uploader.upload(thumbnail,(result) => {
         // return the result
         resolve(result);
       });
    })
  );
})
// do all async actions and store the result in result array
const result = PromiseArr.all();