2017-07-29 205 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' 
}