无法捕获打字稿方法的部分结果

时间:2018-10-05 17:29:50

标签: javascript typescript asynchronous promise async-await

我正在像下面那样调用函数createUser(....)

let response=  this.createUser(email,false,"+"+phoneNumber,password,displayName,false);

这是函数。

createUser(email:string, emailVerified:boolean, phoneNumber:string, password:string, displayName:string, disabled:boolean ) {
    admin.createUser({
        email: email,
      emailVerified: emailVerified,
      phoneNumber: phoneNumber,
      password: password,
      displayName: displayName,
      disabled: disabled
     })
      .then(function(userRecord) {
        // See the UserRecord reference doc for the contents of userRecord.
        console.log("Successfully created new user:", userRecord.uid);
        return Promise.resolve(userRecord);
      })
      .catch(function(error) {
        console.log("Error creating new user:", error);
        return Promise.reject;
     });
     return null;
 } 

但是我想捕获createUser返回的结果,该结果是在该方法的then部分下创建的。 如何捕获它的结果,即在async变量中进行response调用?

1 个答案:

答案 0 :(得分:0)

首先,您需要像这样返回createUser函数内部:

// ...
function createUser( /*params omitted*/ ) {
  return admin.createUser({ // <-- notice the return here
      // ...
    })
    .then(function(userRecord) {
      //...
      return Promise.resolve(userRecord);
    })
    .catch(function(error) {
      // ... remember return the error data too
    });
  // return null;
}
// ...

现在您可以得到如下结果:

1。在async function内使用await

async function getValue() {
  let response = await this.createUser( /*params*/ );
}

演示:

function resolveAfter2Seconds() { 
  return new Promise(resolve => {
    setTimeout(() => {
      resolve("sample data after 1 second");
    }, 1000);
  });
}

async function f1() {
  var x = await resolveAfter2Seconds();
  console.log(x);
}
f1();

2。在then表达式(来自Promise.resolve)中使用回调的常规函数​​中:

function getValue() {
  this.createUser( /*params*/ ).then(function(userRecord) {
    let response = userRecord;
  });
}

演示:

function resolveAfter2Seconds() { 
  return new Promise(resolve => {
    setTimeout(() => {
      resolve("sample data after 1 second");
    }, 1000);
  });
}

function f1() {
  resolveAfter2Seconds(10).then(function(sampleData) {
     console.log(sampleData);
  });
}

f1();