如何使用异步等待包装回叫? [英] How do i wrap a callback with async await?

查看:93
本文介绍了如何使用异步等待包装回叫?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的函数解析了一个承诺,该承诺将在http服务器启动时立即解决.这是我的代码:

My function resolves a promise that resolves as soon as the http server starts. This is my code:

function start() {
    return new Promise((resolve, reject) {
        this.server = Http.createServer(app);
        this.server.listen(port, () => {
            resolve();
        });
    })
}

如何将启动功能转换为异步/等待?

How do i convert the start function to async/await?

推荐答案

在函数声明之前包含async,在await中包含Promise构造函数.尽管要注意,实际上您将在现有模式中添加代码.尽管Question上的代码已经使用了Promise构造函数,但await会将值转换为Promise.

Include async before the function declaration and await the Promise constructor. Though note, you would essentially be adding code to the existing pattern. await converts a value to a Promise, though the code at Question already uses Promise constructor.

async function start() {
    let promise = await new Promise((resolve, reject) => {
        this.server = Http.createServer(app);
        this.server.listen(port, () => {
            resolve();
        });
    })
    .catch(err => {throw err});

    return promise
}

start()
.then(data => console.log(data))
.catch(err => console.error(err));

这篇关于如何使用异步等待包装回叫?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆