应该由Promise调用同步代码。然后创建一个新的Promise

时间:2016-08-05 19:50:09

标签: javascript node.js es6-promise

我已经实现了一些代码,其中异步代码后跟一些同步函数。例如:

function processSomeAsyncData() {
  asyncFuncCall()
    .then(syncFunction)
    .catch(error);
}

如果我理解正确then也是承诺。那么,我应该在同步代码中创建一个承诺吗?

function syncFunction() {
  const p = new Promise (function (resolve, reject) {
    //Do some sync stuff
    ...
    resolve(data);
  }
  return p;
}

如果没有必要,如果发生错误,如何拒绝来自同步代码的承诺?

3 个答案:

答案 0 :(得分:6)

您无需明确创建新承诺。有一种更简单的方法。

这个例子是设计的,因为它永远不会失败,但重点是你不必创建一个承诺,你不必返回一个解决方案(val)。

function syncFunction() {
  var j = "hi"
  if(j){
    return j;
  }
  return new Error('i am an error');
}

这将有效:

asyncFunction()
  .then(syncFunction);

但如果你反过来这样做了:

syncFunction()
  .then(asyncFunction);

您必须将syncFunction定义为:

function syncFunction() {

  var j = "hi"
  return new Promise((resolve, reject) => {
    if(j){
      return resolve(j);
    }
    return reject('error');
  })  
}

编辑:要向所有非信徒证明,请在电脑上给这个家伙一个机会。证明您有这么多选项可供您使用。 :)

var Promise = require('bluebird');


function b(h) {
    if(h){
        return h;
    }
    return Promise.resolve('hello from b');
}

function a(z) {
    return new Promise((resolve, reject)=> {
        if(z){return resolve(z)};
        return resolve('hello from a');
    })
}

a().then(b).then(x => console.log(x)).catch(e => console.log(e));
b().then(a).then(x => console.log(x)).catch(e => console.log(e));

答案 1 :(得分:3)

这是可选的。

如果您从syncFunction返回承诺,那么您的原始承诺将在新承诺结算后解决,并且新承诺返回的任何值将传递给链中的下一个then

如果您返回非Promise值,那么该值将传递给链中的下一个then

要从syncFunction中拒绝,只需抛出异常。

答案 2 :(得分:2)

没有。可以从同步代码调用同步函数,并且应该始终同步失败!它们不需要以任何方式符合异步调用者。如果发生错误,则抛出错误。试试吧:

. sysuse auto, clear
(1978 Automobile Data)

. saveold auto, version(12) replace
(saving in Stata 12 format, which can be read by Stata 11 or 12)
file auto.dta saved

. 
. rsource, terminator(XXX)
Assumed R program path: "/usr/local/bin/R"

Beginning of R output
>         library("foreign")
>         mydata<-read.dta("~/Desktop/auto.dta")
>         mydata$rep78 <- relevel(as.factor(mydata$rep78), ref = 4)
>         m1<-lm(price ~ rep78,data = mydata)
>         summary(m1)

Call:
lm(formula = price ~ rep78, data = mydata)

Residuals:
    Min      1Q  Median      3Q     Max 
-3138.2 -1925.2 -1181.5   369.5  9476.8 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept)   6071.5      702.4   8.643 2.38e-12 ***
rep781       -1507.0     2221.3  -0.678    0.500    
rep782        -103.9     1266.4  -0.082    0.935    
rep783         357.7      888.5   0.403    0.689    
rep785        -158.5     1140.6  -0.139    0.890    
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 2980 on 64 degrees of freedom
  (5 observations deleted due to missingness)
Multiple R-squared:  0.01449,   Adjusted R-squared:  -0.0471 
F-statistic: 0.2353 on 4 and 64 DF,  p-value: 0.9174

> 
End of R output

. 
. /* Old Way */
. char rep78[omit]4

. xi: reg price i.rep78
i.rep78           _Irep78_1-5         (naturally coded; _Irep78_4 omitted)

      Source |       SS           df       MS      Number of obs   =        69
-------------+----------------------------------   F(4, 64)        =      0.24
       Model |  8360542.63         4  2090135.66   Prob > F        =    0.9174
    Residual |   568436416        64     8881819   R-squared       =    0.0145
-------------+----------------------------------   Adj R-squared   =   -0.0471
       Total |   576796959        68  8482308.22   Root MSE        =    2980.2

------------------------------------------------------------------------------
       price |      Coef.   Std. Err.      t    P>|t|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
   _Irep78_1 |      -1507   2221.338    -0.68   0.500    -5944.633    2930.633
   _Irep78_2 |   -103.875   1266.358    -0.08   0.935    -2633.715    2425.965
   _Irep78_3 |   357.7333   888.5353     0.40   0.689     -1417.32    2132.787
   _Irep78_5 |     -158.5   1140.558    -0.14   0.890    -2437.026    2120.026
       _cons |     6071.5   702.4489     8.64   0.000     4668.197    7474.803
------------------------------------------------------------------------------

. 
. /* Post-Stata 11 Way */
. reg price ib4.rep78

      Source |       SS           df       MS      Number of obs   =        69
-------------+----------------------------------   F(4, 64)        =      0.24
       Model |  8360542.63         4  2090135.66   Prob > F        =    0.9174
    Residual |   568436416        64     8881819   R-squared       =    0.0145
-------------+----------------------------------   Adj R-squared   =   -0.0471
       Total |   576796959        68  8482308.22   Root MSE        =    2980.2

------------------------------------------------------------------------------
       price |      Coef.   Std. Err.      t    P>|t|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
       rep78 |
          1  |      -1507   2221.338    -0.68   0.500    -5944.633    2930.633
          2  |   -103.875   1266.358    -0.08   0.935    -2633.715    2425.965
          3  |   357.7333   888.5353     0.40   0.689     -1417.32    2132.787
          5  |     -158.5   1140.558    -0.14   0.890    -2437.026    2120.026
             |
       _cons |     6071.5   702.4489     8.64   0.000     4668.197    7474.803
------------------------------------------------------------------------------

. fvset base 4 rep78

. reg price i.rep78

      Source |       SS           df       MS      Number of obs   =        69
-------------+----------------------------------   F(4, 64)        =      0.24
       Model |  8360542.63         4  2090135.66   Prob > F        =    0.9174
    Residual |   568436416        64     8881819   R-squared       =    0.0145
-------------+----------------------------------   Adj R-squared   =   -0.0471
       Total |   576796959        68  8482308.22   Root MSE        =    2980.2

------------------------------------------------------------------------------
       price |      Coef.   Std. Err.      t    P>|t|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
       rep78 |
          1  |      -1507   2221.338    -0.68   0.500    -5944.633    2930.633
          2  |   -103.875   1266.358    -0.08   0.935    -2633.715    2425.965
          3  |   357.7333   888.5353     0.40   0.689     -1417.32    2132.787
          5  |     -158.5   1140.558    -0.14   0.890    -2437.026    2120.026
             |
       _cons |     6071.5   702.4489     8.64   0.000     4668.197    7474.803
------------------------------------------------------------------------------

这是有效的,因为传递给var asyncFuncCall = () => Promise.resolve(); function syncFunction() { throw new Error("Fail"); } asyncFuncCall() .then(syncFunction) .catch(e => console.log("Caught: " + e.message));的函数抛出的异常被转换为对它应该返回的promise的拒绝。

此外,传递给.then的函数返回的任何值都将转换为使用该值解析的promise。调用函数的promise代码负责处理这个问题。

这使您可以毫无问题地混合同步和异步代码:

.then