我正在像下面那样调用函数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
调用?
答案 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();