所以,我知道之前已经问过这个问题,我尝试过其他答案,例如.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
一个例子真的会有所帮助,显然,更改值会涉及一些异步函数。
答案 0 :(得分:1)
将数组中对象的"thumbnail"
属性设置为result.public_id
。创建一个函数,其中期望参数是postsData
数组中的当前对象,通过将函数引用传递给"thumbnail"
函数来设置对象的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:[{}]}
);
}
答案 1 :(得分:0)
据我所知,您正在尝试遍历数组并对其每个元素执行异步函数。我要做的是使用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();