1

在 WinJS 中,如果您需要“突破”链,链式 Promise 的正确方法是什么?例如,如果您有 .then() 函数和最终的 .done()。从之后有其他人的 then 返回错误的正确方法是什么?

考虑以下伪代码示例

 function doSomething(){
  return new WinJS.Promise(function(comp,err,prog){

  filePicker.pickSingleFileAsync().then(function(file){
         if(file){ // have a valid file
              return  readTextAsync(File);
         }else{ //else user clicked cancel
              return err('No file');
         }
  }).then(function(text){
              if(text){
                   return comp(text);
              }else{
                  return err('No text');
              }
  }).done(null, function(error){ //final done to catch errors
      return err(error);
  });


  });// end return promise
} //end doSomething();

 doSomething().done(function(text){
        console.log(text);
 }, function(err){
        console.log(err);
 });

现在在这个简化的例子中,如果用户取消 filePicker,他们应该点击第一个 err("No File"); 然而,这仍然会继续调用下一个 .then(text),它也会返回一个错误('no text'),因为 text 是未定义的。整体 doSomething().done() 错误处理程序在此处返回“No File”,这是我所期望的,但调试显示代码仍然调用 promise 的“err('No Text')”部分。此时是否有可能真正退出承诺链?我应该看看如何在这里使用任何方法吗?

谢谢

* * *编辑。如果其他人想根据下面接受的答案知道我的解决方案是什么样的,如下所示:

      filePicker.pickSingleFileAsync().then(function (file) {
            if (file) {
                return Windows.Storage.FileIO.readTextAsync(file);
            }               
            return WinJS.Promise.wrapError("No File");
        }).then(function (text) {
            if (text) {
                return complete(text);
            }
            return error("no text");
        }).done(null, function (err) {
            return error(err);
        });
4

3 回答 3

4

用于WinJS.Promise.wrapError向承诺链返回错误。

在您的示例中,如果中途出现真正的“错误”,您可以选择仅在最后处理错误。

这也使您有机会“纠正”错误,并允许“成功案例”继续进行——如果您从错误处理程序中返回一个值,该值将沿着成功链传播。

于 2012-12-04T22:31:09.937 回答
0

我不完全确定,但尝试只调用 err('No text') 而不是“return err('...')”。

于 2012-12-04T20:33:13.510 回答
-1

如果你要使用 winjs.promise.wraperror,你应该像这样提供错误处理程序

somepromise()
.then(
        function(){ return someAsyncop()},
        function(error){
         somelogfunction("somepromise failed");
         return WinJS.Promise.wrapError(error);
        })
.then(
        function(){ somelogfunction("someAsyncop done ok"); return WinJS.Prmoise.wrap();},
        function(error){
         somelogfunction("someAsyncop failed"); return WinJS.Promise.wrap();
        })
.done(function(){ //dosomtehing });


或使用try catch构造

try{
somepromise()
.then(  function(){ return someAsyncop()})
.then(  function(){
         somelogfunction("someAsyncop done ok");
         return WinJS.Prmoise.wrap();}
     )
.done( function(){ //dosomtehing});
}
catch(e){
        somelogfunction(e.message);
}
于 2016-04-07T09:30:32.377 回答