首页 > 解决方案 > 承诺完成后如何恢复功能?

问题描述

我正在尝试设置一个链接到数据库的 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;
}

谢谢 :)

标签: javascriptmysqlpromise

解决方案


第一次使用 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);
}

推荐阅读