gpt4 book ai didi

javascript - 存储已解决的 promise 项目

转载 作者:行者123 更新时间:2023-12-02 15:17:24 24 4
gpt4 key购买 nike

下午好,

我在 Parse Javascript 中遇到了障碍,试图在循环中将项目放入 Promise 后存储项目。在图片循环之外,对象数组是空的。

.. define global ** var filesUpload = []**

for (var key in files) {
var photoUpload = new Parse.File(String(file.name),[file.image])
photoUpload.save().then(function(item) {
deferred.resolve(item)

filesUpload.push(deferred.promise)


}, function(error) {
console.log("error to save file"+JSON.stringify(error))
// The file either could not be read, or could not be saved to Parse.
})
}

--> 结束循环

文件上传为空

最佳答案

如果您需要获取多个 Promise 的值,则必须使用 Promise.all。现在,Parse.com 似乎没有 Promise.all 实现,但他们确实有类似的东西:

Parse.Promise.when(files.map(function(file){
return new Parse.File(String(file.name),[file.image]).save();
})).then(function(){
var results = Array.prototype.slice.call(arguments);
//results === your filesUpload
}).then(null, function(err){
console.log("error to save file" + JSON.stringify(error));
});

如果您更喜欢Promise.all:

Promise.all(files.map(function(file){
return new Parse.File(String(file.name),[file.image]).save();
})).then(function(results){
//results === your filesUpload
}).catch(function(err){
console.log("error to save file" + JSON.stringify(error));
});

我还使用了 Promise.prototype.catch,它在 Parse.Promise 实现上也不可用,但大多数 Promise 确实实现了此方法。例如,ES6 Promise 有两种方法:Promise.allPromise.prototype.catch

关于javascript - 存储已解决的 promise 项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34337902/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com