Node.js中Express框架使用axios同步請求(async+await)實現(xiàn)方法
axios一般是作為異步請求使用的,但是某種特殊情況下需要同步請求,如何實現(xiàn)呢?
首先定義一個方法syncAxios
let axios = require('axios'); exports.syncAxios = function (obj = {}) { let url = "http://www.rrbay.com/api/"; return new Promise((resolve, reject) => { axios(url, { method: 'POST', timeout: 5000, params: { sProcName: obj.sProcName, idNo: obj.id, userName: obj.qq, overTime: obj.endTime } }).then((res) => { resolve(res.data); }).catch((error) => { reject(error) }) }) };
然后在controllers 調(diào)用
exports.check = function (req, res) { //定義async方法體 XXXMode.findById(id).populate('author').exec(async function (err, result) { let dataCode = false; if(result.status ==0){ //同步調(diào)用 await baseapi.syncAxios({ sProcName: 'Update', id: '000000-1111-2222-3333-9999999', qq: '391502069',//result.author.name, endTime: '2022/12/31 11:39:05'//result.EndTime }).then((data) => { console.log(data, 'res'); }).catch((err) => { console.log(err && err.stack); }); } result.save(function (err, onewxtob) { if (req.xhr) { return res.json({ status: !err }) } }); }); };
view中使用模板引擎jade,需要在請求check
后,延遲刷新頁面顯示請求結(jié)果
setTimeout(function () { $(location).attr('href',window.location.href) }, 1000)
這里的setTimeout實現(xiàn)了延遲加載刷新頁面的效果,結(jié)合控制器的交互,最終實現(xiàn)了同步操作的效果。
相關(guān)文章
Node.js中文件系統(tǒng)fs模塊的使用及常用接口
fs是filesystem的縮寫,該模塊提供本地文件的讀寫能力,基本上是POSIX文件操作命令的簡單包裝。這篇文章主要介紹了Node.js中的文件系統(tǒng)fs模塊的使用,需要的朋友可以參考下2020-03-03Node.js使用Express創(chuàng)建Web項目詳細教程
如果需要入門使用node.js進行web開發(fā),正在學(xué)習(xí) nodejs web開發(fā)指南 的和想快速了解node.js web開發(fā)模式的朋友,相信本文是有一定幫助意義的。2017-03-03node.js中的http.request.end方法使用說明
這篇文章主要介紹了node.js中的http.request.end方法使用說明,本文介紹了http.request.end的方法說明、語法、接收參數(shù)、使用實例和實現(xiàn)源碼,需要的朋友可以參考下2014-12-12npm安裝淘寶鏡像報錯問題解決(npm install -g cnpm)
本文主要介紹了npm安裝淘寶鏡像報錯問題解決,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-01-01使用基于Node.js的構(gòu)建工具Grunt來發(fā)布ASP.NET MVC項目
這篇文章主要介紹了使用基于Node.js的構(gòu)建工具Grunt來發(fā)布ASP.NET MVC項目的教程,自動化構(gòu)建工具Grunt具有編譯壓縮單元測試等功能,十分強大,需要的朋友可以參考下2016-02-02深入理解nodejs搭建靜態(tài)服務(wù)器(實現(xiàn)命令行)
這篇文章主要介紹了深入理解nodejs搭建靜態(tài)服務(wù)器(實現(xiàn)命令行),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-02-02Node.js 中exports 和 module.exports 的區(qū)別
這篇文章主要介紹了Node.js 中exports 和 module.exports 的區(qū)別的相關(guān)資料,需要的朋友可以參考下2017-03-03