2017-07-29 202 views
0

我目前有一个项目,它使用本地承诺。我期待将这些Promise迁移到Async/Await。我有麻烦迁移他们;我正在尝试关注this文章。以下是Promise需要更改为Async/Await的当前代码。Node.JS - 承诺异步/等待示例

routes.js

// Importing user information 
import user from '../server-controllers/user'; 

// User Information Route 
router.get('/about', (req, res) => { 
    user.profile().then((data) => { 
    return res.render('user', { 
     title: data, 
    }); 
    }).catch((e) => { 
    res.status(500, { 
     error: e, 
    }); 
    }); 
}); 

user.js的

/* 
This file contains any server side modules needed. 
*/ 

module.exports = { 
// Returns information about a user 
    profile:() => { 
    return new Promise((resolve, reject) => { 
     const user = "John Doe"; 
     resolve(user); 
    }); 
    }, 
}; 

如果有什么我需要做的这些转换,这将是有帮助的任何帮助。我不知道代码是否需要更改routesuser文件(或两者)。

,我在我的终端正的错误是[object Error] { ... }

+0

这里的整个应用程序与异步/ AWAIT:https://开头github.com/bryanmacfarlane/sanenode – bryanmac

+0

只需用'await'替换每个'then'调用即可。 – Bergi

回答

3

要记住asyncawait是一个async功能实际上只是一个返回Promise的功能,使您可以使用await解决事情的关键Promise s。所以当Promise拒绝时,如果是await ed,那么在await的任何地方都会出现错误。

所以从技术上说,如果你想使用async/await语法,你不需要改变user.js。你可以只改变routes.js到:

// Importing user information 
import user from '../server-controllers/user' 

// User Information Route 
router.get('/about', async (req, res) => { 
    try { 
    const data = await user.profile() 
    return res.render('user', { 
     title: data 
    }) 
    } catch (error) { 
    // Runs if user.profile() rejects 
    return res.status(500, {error}) 
    } 
}) 

user.js当您使用async功能更加简单明了:

module.exports = { 
    // Returns information about a user 
    // This returns a Promise that resolves to 'John Doe' 
    profile: async() => 'John Doe' 
}