我有一个 Flutter 应用程序,我正在尝试从 Braintree 获取客户端随机数。根据 braintree documentation ,我的云函数中有这个:
exports.getClientNonce = functions.https.onCall(async (data, context) => {
gateway.clientToken.generate({}, function (err, response) {
if (err) {
throw new functions.https.HttpsError('unknown', 'Error getting client nonce');
} else {
console.log(`token: ${response.clientToken}`);
return response.clientToken;
}
});
});
然后,在我的 Flutter 应用程序中,我调用该函数(同样,我遵循 plugin says 的内容):
try {
HttpsCallable callable = CloudFunctions.instance.getHttpsCallable(
functionName: 'getClientNonce',
);
dynamic result = await callable.call({});
final value = result.data;
debugPrint('token: $value');
var data = await BraintreePayment().showDropIn(
nonce: value,
amount: '2.0',
enableGooglePay: false,
inSandbox: true);
print("Response of the payment $data");
} on CloudFunctionsException catch (e) {
debugPrint('An error occurred');
} catch (e) {
debugPrint('An error occurred');
}
}
我尝试更改云函数,使其仅返回一个随机数(函数执行后立即返回),并且我的 Flutter 应用程序正确接收该值(因此云函数通信正常)。在我的 Firebase 控制台中,我可以查看 console.log
指定的客户端随机数。但该函数出于某种原因无法返回实际的客户端随机数。 (它应该是一些>2000个字符长的字符串哈希)
最佳答案
可调用函数需要从函数回调的顶层返回一个 promise ,该 promise 将解析为要返回的值。现在,您没有从顶层返回任何内容。您现在得到的返回只是从传递给 Braintree API 的内部回调函数返回一个值。这不会传播到顶层。
您需要做的是使用返回 API 的 Braintree API 版本(如果存在),或者 promisify使用回调的现有调用。
另请参阅“3. Node 样式回调”:How do I convert an existing callback API to promises?
我还没有对此进行测试,但是如果您应用该模式,一般格式将看起来更像这样:
exports.getClientNonce = functions.https.onCall(async (data, context) => {
return new Promise((resolve, reject) => {
gateway.clientToken.generate({}, function (err, response) {
if (err) {
reject(new functions.https.HttpsError('unknown', 'Error getting client nonce'));
} else {
console.log(`token: ${response.clientToken}`);
resolve(response.clientToken);
}
});
});
});
关于javascript - https可调用云函数不返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58262800/