javascript - Promise 同步函数

标签 javascript promise es6-promise

所以,我有一个类似这样的代码。

     getSomethingAsync(something)
     .then(doSomethingAsync)
     .then(function(d) {
     _d = doSomethingSync(d);
     return doSomethingAsyncNext(_d);
     })
     .then(function(val) {
      //All done
      })
      .catch(err_handler);

我想把它变成类似的东西。

     getSomethingAsync(something)
     .then(doSomethingAsync)
     .then(doSomethingSync)
     .then(doSomethingAsyncNext)
     .then(function(val) {
      //All done
      })
      .catch(err_handler);

我应该改变 doSomethingSync 吗:

      function(data) {
      // do a lot of things with data, throw errors for invalid data
      return changed_data;
      }

至:

      function(data) {
      // do a lot of things with data, throw errors for invalid data
      return new Promise(function(resolve,reject){
      resolve(changed_data);
      });
      }

或者:

      function(data) {
      return new Promise(function(resolve,reject){
      // do a lot of things with data, reject for invalid data
      resolve(changed_data);
      });
      }

最佳答案

Should I just change doSomethingSync which is ...

您不必全部更改。如果回调的返回值不是一个promise,则直接用于解析.then返回的promise。 .then 回调没有返回一个promise。

可以

return Promise.resolve(changed_data);

但同样,没有必要。 returnchanged_data; 也同样有效。

关于javascript - Promise 同步函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31367071/

相关文章:

javascript - 我应该在调度时捕获 Redux promise 错误还是只在 reducer 中处理它?

javascript - 如何播放不带扩展名 video.js 的流 URL

javascript - Node.js:使用 Bluebird 将模块函数从回调转换为 Promise

javascript - 带有 node.js promise 的 RPC

node.js - 如果使用 Promise 存在对象,则 AWS 签名 url

javascript - axios 和 promises,数组值不可用但出现在 console.log 中

javascript - 将 Fetch API 与 Promise.all 结合使用

javascript - 根据其他对象的数组属性对对象数组进行排序的最快方法

javascript - 如何将 3 个不同 div 的可见性切换为三个相应的 div

javascript - ">>"和 "<<"在 Javascript 中是什么意思?