存储承诺项目已解决

时间:2015-12-17 15:11:37

标签: javascript parse-platform promise

下午好,

我在Parse Javascript中遇到了一个墙,试图在循环中获得它们之后存储项目。在图片循环之外,对象数组是无效的。

.. 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.
            })
         }

- >结束循环

filesUpload为空

2 个答案:

答案 0 :(得分:2)

如果您需要获取多个承诺的值,则必须使用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.catchParse.Promise实现中不可用,但大多数promises都会实现此方法。例如,ES6 Promises有两种方法,Promise.allPromise.prototype.catch

答案 1 :(得分:0)

Promise是异步的,这意味着在for循环之后立即出现的任何代码在解析promise并且调用then函数之前运行。

好像你做了这样的事情:



window.setTimeout(function() {
  document.write('inside setTimeout');
}, 1000);

document.write('after call to setTimeout');




无论您需要对filesUpload执行什么操作,都需要在then承诺的photoUpload.save()回调中执行此操作。你可以提取一个函数并从那里调用它。



 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)
     goAhead();

   }, 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.
   })
 }

 function goAhead() {
   // go ahead
 }




相关问题