应该由Promise调用同步代码,然后创建一个新的Promise [英] Should synchronous code called by Promise .then create a new Promise

查看:93
本文介绍了应该由Promise调用同步代码,然后创建一个新的Promise的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实现了一些代码,其中异步代码后跟一些同步功能。例如:

I've implemented some code, where asynchronous code is followed by some synchronous functions. For example:

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

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

If I understand correctly then is also a Promise. Then, should I create a promise in the synchronous code as well?

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

如果没有必要,如何在同步代码中拒绝承诺

If that isn't necessary, how do you reject the promise from the synchronous code if an error occurred?

推荐答案

您不需要显式创建新的Promise,这是一种更简单的方法。

You don't need to create a new promise explicitly. There is an easier way.

该示例是人为设计的,因为它永远不会失败,但要点是您不必创建承诺,也不必返回resolve(val)。

This example is contrived because it will never fail, but the point is that you don't have to create a promise and you don't have to return a resolve(val).

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

这将起作用:

asyncFunction()
  .then(syncFunction);

但是如果您反过来这样做:

But if you did it the other way around:

syncFunction()
  .then(asyncFunction);

您必须将syncFunction定义为:

You would have to define your syncFunction as:

function syncFunction() {

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

编辑:要向所有人证明所有非信徒,请在本地给这个人一个镜头你的电脑。证明您有许多可用的选项。 :)

To prove to all you non believers out there, give this guy a shot locally on your computer. Proves that you have these many options available to you. :)

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));

这篇关于应该由Promise调用同步代码,然后创建一个新的Promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆