2017-04-11 68 views
0

所以,我知道这已经问过,我已经试过像.map(function(post){ async })(value)其他答案,我仍然停留...的Javascript:对象的数组,每个对象改变值异步

所以,我有对象和数组的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 

一个例子将真正帮助,因为很明显,得到的值更改涉及到一些异步函数。

+1

你'postsData'是无效的 - 也许这是一个起点(值应弦) –

回答

1

"thumbnail"设置为result.public_id。创建的函数,其中预期参数是postsData阵列内当前对象,通过传递函数参照upload函数,传递利用阵列prop对象的当前对象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:[{}]} 
); 
} 

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

+0

试过了,但不幸的是,当我为以后叫postsData的,缩略图仍然一样...... – Daltron

+0

_“试过了,但不幸的是,当我在for后调用postsData时,缩略图仍然是相同的。”_什么时候在'console'上记录'postsData'? 'Cloudinary.uploader.upload'回调函数异步设置'result',是吗? 'let thumbnail = postsData.thumbnail;'在Cloudinary.uploader.upload()调用之前可能需要''缩略图''undefined'在Answer的'javascript'。 – guest271314

+0

所以,我尝试了使用for-prop-loop,其中'let thumbnail = prop.thumbnail;'然后我调用'console.log(postsData);'在for-prop-loop之后,你的例子wasn使用for(i ++)循环,所以我删除了......但我仍然以相同的postsData数组结束。 – Daltron

0

从设定对象的"thumbnail"属性什么我明白,你正试图循环访问一个数组,并在其每个元素上执行异步函数。我会做的是使用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(); 
相关问题