2017-04-11 97 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();