使用promise链接同步与异步功能时的工作流

Workflow when chaining synchronous with asynchronous function with promises

本文关键字:功能 工作流 异步 promise 链接 同步 使用      更新时间:2023-09-26

如果我用promise链接同步和异步函数,工作流会是什么样子?

案例1:

synchronousFunc(x).then(asynchronousFunc(resultOfSynchronousFunc));

同步Func(x(

|----------|

异步Func(未定义(

|---------------|

案例2:

asynchronousFunc(x).then(synchronousFunc(resultOfAsynchronousFunc));

异步Func(x(

|--------|

synchronousFunc(未定义(

|-------------|

案例3:

 asynchronousFunc(x).then(function(){
  return synchronousFunc(resultOfAsynchronousFunc);
 });

异步Func(x(

|---------|

synchronousFunc(AsynchronousFunc的结果(

………|------------------|

案例4:

 synchronousFunc(x).then(function(){
  return asynchronousFunc(resultOfSynchronousFunc);
 });

同步Func(x(

|---------|

异步Func(未定义(

|------------|

Lets-put异步函数是一个返回promise(或then-可对象,请参阅MDN(的函数。同步函数是一个返回任何其他结果(非二进制(的函数。

异步函数返回promise"immediate">,即在promise被解析之前(promise状态为"pending">,尚未调用then(。

funcSync(x).then(funcAsync) // Error if `funcSync` returns object without `then` method.
// Should be:
var res = funcSync(x);
var promise = funcAsync(res);

promise.then(..)作为一个自变量,取一个对异步函数的结果起作用的函数:fetchDataAsync.then( data => {..} )
情况2应该是:

fetchDataAsync(x).then(processDataSync);

修复你所有的案例太平凡了,请阅读MDN。