如何解决承诺功能

时间:2020-02-21 11:03:59

标签: javascript jquery reactjs redux react-redux

如何在承诺后显示结果?我在console.log("the result is==>", result)中看到了结果,但是在promise.then下却看不到控制台。

const signIn = (password) => {
  var request = new DeviceAuthQuery();
  request.setPassword(password);
  let result;

  var response = client.authenticate(request, {}, (err, response) => {
    console.log("Request Sent 1111");
  });

  let promise = new Promise(() => {
    response.on('data', function(reply) {
      console.log('Data: 22222' + reply.getAuthjwt());
      result = reply.getAuthjwt();
      console.log("the result is==>", result)
      promise.resolve(true);
    });
  });

  promise.then(() => {
    console.log("the result ZZZZZ==>", result)
  })

2 个答案:

答案 0 :(得分:0)

您错过了回调结果:

let promise = new Promise((resolve) => {
   response.on('data', function(reply) {
     console.log('Data: 22222' + reply.getAuthjwt());
     result = reply.getAuthjwt();
     console.log("the result is==>", result)
     resolve(true);
   });
});

promise.then((result) => {
  console.log("the result ZZZZZ==>", result)
})

答案 1 :(得分:0)

您应该在提供给Promise构造函数的函数中使用参数,以便解析/拒绝承诺。然后,您只需将数据作为参数传递给这些数据即可。这是一个基本示例:

const signIn = () => {
  var promise = new Promise((resolve, reject) => {
    setTimeout(function() {
      resolve("Foo Bar");
    }, 2000)
  });

  promise.then((result) => {
    console.log("the result ZZZZZ==>", result)
  })
}

signIn();