将回调函数传递给promise.then()

时间:2019-01-17 23:52:50

标签: javascript

当调用myFunction中的回调函数时,调用方函数是否像myFunciton.then()这样进行调用?我可以说第一个在myFunction被解析时触发,而第二个回调函数在myFunction失败时被调用吗?

 myFunciton: function() {    
     const myPromise = myService.loadData(oParams);    
     myPromise.then(() => {
          //do something
     }, () => {
          //do something else
     });
     return myPromise;   
 }         

2 个答案:

答案 0 :(得分:1)

Promise是一种状态机,具有几种潜在状态:挂起(初始状态),已实现和已拒绝。

创建新的Promise时,您将提供一个接受两个参数的回调,这两个函数分别解析和拒绝。决定进入已完成状态,拒绝进入已拒绝状态,并且如果您的承诺包装的代码引发异常,则承诺也会进入被拒绝状态。一旦解决或被拒绝,您的诺言将存储返回的值以供后续解决。

现在,无论何时调用myPromise.then,myPromise.catch或提供回调函数。承诺会在内部检查其状态。

如果promise未完成,它将在您的处理程序中排队,并且在引发拒绝,解决或异常的调用时,它将循环访问排队的处理程序并调用适当的处理程序(取决于已解决还是被拒绝) )。

现在,如果已完成或拒绝了诺言,则诺言将异步调用适当的处理程序。

让我们看看您的代码:

 myFunction: function() {  
     const myPromise = myService.loadData(oParams);  
     // handlers are queued if myPromise is pending
     // function passed to then is called asynchronously if resolved
     // callback will be called asynchronously if rejected
     myPromise.then(() => {
          //do something
     }, () => {
          //do something else
     });
     return myPromise;   
 }         

现在,您将询问何时调用回调。

// This will trigger the execution of myService.loadData
// As pointed out in the comments above your callbacks will either be queued, or 
// called asynchronously.
// The value of myPromiseResult will always be a promise(pending, resolved, or    // rejected)
const myPromiseResult = myFunction();

// Here's the cool part, since promises are essentially a state machine
// every subsequent callback will yield the same result
myPromiseResult.then(() => {
    // if the callback pass to myPromise.then is called within myFunction
    // this will be called as well, and if you were passing a result
    // it would have the same result as well
}, () => {
   // if the error callback pass to myPromise within myFunction was called
   // then this will be called as well, and as mentioned above would have
   // been passed the same result as well.
});

答案 1 :(得分:-1)

使用该代码,将要解决的第一个诺言将是“ myFunciton”函数中的诺言。然后,如果您使用了myFunciton.then()之类的东西,它将被排在第二位。

希望我能为您提供帮助。