javascript - 承诺完成后如何恢复功能?
问题描述
我正在尝试设置一个链接到数据库的 js Messenger 聊天机器人。当然,有时,用户从数据库向聊天机器人请求数据,我确实使用 Promise 来收集它。我最近了解了它们,所以我只知道基础知识。我的问题是,当 promise 实现时,我不仅需要触发一些代码(通过 then() 函数完成),还需要向主模块返回数据以创建答案。履行诺言后如何恢复我的功能(以达到回报)?我可能很难理解,所以这是我的聊天机器人和我的一些代码的序列图。
应用程序.js
const Database = require("./services/database");
const Message = require("./services/message");
app.get("/endpoint", (req,res)=>{
let message
//Check if the user message request data
if (req == datarequest)
{
message = Database.request();
}
else
{
message = "You did not require any data";
}
Message.sendToUser(message);
});
DBInteractionModule.js
async request()
{
//Creating the promise
let promise = new Promise(
function(){
let connection = db.connect();
return connection.query("SELECT * FROM user;");
}
);
// Only(?) way to use data when it returns
promise.then(function(data)
{
console.log("data requested : "+ data);
});
//I need to use this return in order to give data back to the main app
return promise;
}
谢谢 :)
解决方案
第一次使用 Promise 时会很棘手,但是一旦习惯了它们,就只能等待然后解决或拒绝 Promise。
我假设,db.connect
并且connection.query
都返回一个承诺,所以你必须等待他们履行承诺。
// the `async` word before the functions here is important
const request = new Promise(async (resolve, reject) => {
// wait for the db to connect
let connection = await db.connect();
// wait for the db to return it's data
const data = await connection.query("SELECT * FROM user;");
// after waiting, if no error, the data should be available now
console.log('Requested data (WITHIN the promise) : ', data);
//return the data by resolving the main promise
resolve(data)
});
用法 :
request.then(data => {
console.log('Requested data (OUTSIDE the promise) : ', data);
//Process data
});
或者在另一个异步函数内部:
async function main() {
const data = await request;
console.log('Requested data (OUTSIDE the promise) : ', data);
}
推荐阅读
- mysql - 数据库模式用户匹配
- python - 如何使用 python 3 对文件执行上下文菜单操作
- laravel - Laravel 路由访问类别和显示方法
- ios - 从 web json 解析图像
- php - 在特定位置将元素添加到 PHP 循环中
- bash - 在 bash 中使用 IFS 而不是 whitepace
- android - 在 NestedScrollView 中使用 RecyclerView 为所有项目调用 onBindView
- python-3.x - Selenium 和 Python 3:在 otto.de 上选择搜索框
- android - 在recyclerview的项目中选择多个复选框并将它们保存在Hashmap中
- java - 使用 GSON 按变量键对 JsonArray 进行排序