【问题标题】:I called then() on a TypeScript promise but it is still pending. Why is this? How can I get it to resolve?我在 TypeScript 承诺上调用了 then(),但它仍在等待中。为什么是这样?我怎样才能解决它?
【发布时间】:2019-11-07 17:36:15
【问题描述】:

这是我正在运行的 index.ts 脚本(基于我在 reddit 上找到的内容):

const path = require("path");
const sql = require("mssql");
const config = require(path.resolve("./config.json"));

let db1;

const connect = () => {
    return new Promise((resolve, reject) => {
        db1 = new sql.ConnectionPool(config.db, err => {
            if (err) {
                console.error("Connection failed.", err);
                reject(err);
            } else {
                console.log("Database pool #1 connected.");
                resolve();
            }
        });
    });
};

const selectProjects = async (name) => {
    const query = `
        select * from [Time].ProjectData where [Name] like concat('%', concat(@name, '%'))`;

    const request = new sql.Request(db1);
    const result = await request
        .input("name", name)
        .query(query);

    return result.recordset;
};

module.exports = {
    connect,
    selectProjects
};

connect().then(function() {
    console.log(selectProjects('General'));
}).catch(function(err) {
    console.log(err);
});

当我使用node index 运行脚本时(当然是在编译之后),我在控制台中得到了这个:

Database pool #1 connected.
Promise { <pending> }

然后脚本挂起。

【问题讨论】:

  • 需要注意的是,这不是 typescript Promises 的一个特性,typescript 不会改变 Promise 也不会改变 javascript 的任何底层功能。

标签: javascript typescript promise


【解决方案1】:

显然 await 关键字创建了一个隐含的承诺;我不得不将最后一个函数调用更改为:

connect().then(function() {
    selectProjects('General').then(function(data) {
        console.log(data);      
    });
}).catch(function(err) {
    console.log(err);
});

【讨论】:

  • await 不会创建隐式承诺。您可以在非异步函数上调用await,它不会创建承诺。当您执行 new Promise 或使用 async 关键字时隐式创建 Promise。
  • 所有异步函数都返回一个承诺(按设计)。无论您从函数中手动return,它都将成为异步函数返回的承诺的解析值。因此,在调用任何异步函数时,您必须使用 .then()await 从中获取实际返回值(您似乎已经意识到了这一点)。
猜你喜欢
  • 2018-07-20
  • 2023-03-10
  • 2019-10-23
  • 2019-06-19
  • 2021-12-22
  • 2016-08-28
  • 2021-04-01
  • 2021-12-29
  • 1970-01-01
相关资源
最近更新 更多