返回值取决于javascript中promises的结果

时间:2016-01-22 12:18:19

标签: javascript node.js asynchronous promise

我想要一个根据promises响应返回消息的函数,但我无法获得已解析的值。

function create() {
  var check = promise1();
  var increment = promise2( check );
  var create = promise3( increment );

  if ( create === 1 ) {
    return {
      message: `Item with id ${increment} created`,
      value: 'OK'
    }
  } else {
    return {
      message: `Item not created`,
      value: 'FAIL'
    }
  }
}

var res = create()
  // I want it to return the json if the item was created
  // but instead they return promises and I have to use then
  // I can't think of another way

console.log( res );

如果我向您展示承诺中的代码是什么样的,那会有用吗?

代码要复杂得多,但我试图将其简化到极致。

//解决 编辑:

function create( responsecb ) {
  var check = promise1();
  var increment = promise2( check );
  var create = promise3( increment );

  if ( create === 1 ) {
    responsecb( {
      message: `Item with id ${increment} created`,
      value: 'OK'
    } )
  } else {
    responsecb( {
      message: `Item not created`,
      value: 'FAIL'
    } )
  }
}

create.then(console.log)

我只需要创建一个回复,它可以对响应做些什么。

0 个答案:

没有答案