如何将带有回调的链式承诺代码转换为 async/await
How do I convert this chained promises code with callback to async/await
如何将带回调的链式承诺代码转换为 async/await
我不知道如何将此代码转换为 async/await 以使其更具可读性
var responseCallbacks = {};
bot.onText(/\/something/, async (msg) => {
var callback = responseCallbacks[msg.chat.id];
if (callback) {
delete responseCallbacks[msg.chat.id];
return callback(msg);
}
bot.sendMessage(msg.chat.id, "something").then(() => {
responseCallbacks[msg.chat.id] = (answer) => {
var something = answer.text;
bot.sendMessage(msg.chat.id, "something else").then(() => {
responseCallbacks[msg.chat.id] = (answer) => {
var somethingElse = answer.text;
console.log(something, somethingElse);
};
});
};
});
});
这是你想要的:
var responseCallbacks = {};
bot.onText(/\/something/, async (msg) => {
var callback = responseCallbacks[msg.chat.id];
if (callback) {
delete responseCallbacks[msg.chat.id];
return callback(msg);
}
await bot.sendMessage(msg.chat.id, "something");
responseCallbacks[msg.chat.id] = async (answer) => {
var something = answer.text;
await bot.sendMessage(msg.chat.id, "something else");
responseCallbacks[msg.chat.id] = (answer) => {
var somethingElse = answer.text;
console.log(something, somethingElse);
};
};
});
如何将带回调的链式承诺代码转换为 async/await
我不知道如何将此代码转换为 async/await 以使其更具可读性
var responseCallbacks = {};
bot.onText(/\/something/, async (msg) => {
var callback = responseCallbacks[msg.chat.id];
if (callback) {
delete responseCallbacks[msg.chat.id];
return callback(msg);
}
bot.sendMessage(msg.chat.id, "something").then(() => {
responseCallbacks[msg.chat.id] = (answer) => {
var something = answer.text;
bot.sendMessage(msg.chat.id, "something else").then(() => {
responseCallbacks[msg.chat.id] = (answer) => {
var somethingElse = answer.text;
console.log(something, somethingElse);
};
});
};
});
});
这是你想要的:
var responseCallbacks = {};
bot.onText(/\/something/, async (msg) => {
var callback = responseCallbacks[msg.chat.id];
if (callback) {
delete responseCallbacks[msg.chat.id];
return callback(msg);
}
await bot.sendMessage(msg.chat.id, "something");
responseCallbacks[msg.chat.id] = async (answer) => {
var something = answer.text;
await bot.sendMessage(msg.chat.id, "something else");
responseCallbacks[msg.chat.id] = (answer) => {
var somethingElse = answer.text;
console.log(something, somethingElse);
};
};
});