我知道已经有这样的问题。我保证我已经读过它们;我只是不明白。我有一些简单的代码来获取第三方API服务的令牌:
let tok = '';
const getToken = async () => {
tok = await btt.get();
console.log(tok);
};
getToken();
tok
始终undefined
位于console.log
。我以为await
的全部意思是您的代码将暂停,直到该特定的诺言得到解决或拒绝为止。我误会了吗?这是get
函数:
async get () {
this.paymentGateway.clientToken.generate({
customerId: '5cdc7405da53494ee0f3bafe'
}, (err, result) => {
return new Promise((resolve, reject) => {
if (result.success) {
resolve(result.clientToken);
} else {
reject(result.errors);
}
});
});
}
我在这个特定问题上停留了一段时间,并尝试了许多不同的方法。如果有人可以提供帮助,我将不胜感激。
谢谢。
答案 0 :(得分:3)
您的异步功能未返回承诺。试试这个:
async get () {
return new Promise((resolve, reject) => {
this.paymentGateway.clientToken.generate({
customerId: '5cdc7405da53494ee0f3bafe'
}, (err, result) => {
if (result.success) {
resolve(result.clientToken);
} else {
reject(result.errors);
}
}
});
}
一个例子:
const mockPaymentGateway = {
clientToken: {
// a mock that will randomly succeed and fail.
generate: (_, callback) => callback(null, Math.random() > 0.5 ? {
success: true,
clientToken: '<This is a token value.>'
} : {
errors: ['We have no moneys.']
}),
}
}
// I assume you have other things in your service, but here is an example
class SomeService {
constructor(paymentGateway) {
this.paymentGateway = paymentGateway;
}
async get() {
return new Promise((resolve, reject) => {
this.paymentGateway.clientToken.generate({
customerId: '5cdc7405da53494ee0f3bafe'
}, (err, result) => {
if (result.success) {
resolve(result.clientToken);
} else {
reject(result.errors);
}
});
});
}
}
// Generating mock data...
const btt = new SomeService(mockPaymentGateway);
let tok = '';
const getToken = async() => {
try {
tok = await btt.get();
console.log(tok);
} catch (e) {
console.log('Errors getting token:', e);
}
};
document.querySelector('#get-token').addEventListener('click', async() => {
console.log('Getting token');
getToken()
});
<button id="get-token">Get token</button>
答案 1 :(得分:2)
在Promise中打个电话:
async get () {
return new Promise((resolve, reject) => {
this.paymentGateway.clientToken.generate({
customerId: '5cdc7405da53494ee0f3bafe'
}, (err, result) => {
if (result.success) {
resolve(result.clientToken);
} else {
reject(result.errors);
}
});
});
}
答案 2 :(得分:0)
您从未兑现诺言。将最后一行更改为此:
getToken().catch(console.error);