以后如何在其他函数中使用Promise返回的数据

时间:2019-01-15 17:07:32

标签: javascript asynchronous promise async-await

test

我有显示的代码,我想在另一个js文件中使用getOrderdata函数吗?

1 个答案:

答案 0 :(得分:0)

将函数放在module.exports对象中,并在导入文件中使用async-await函数。

// file exporting the function - exp.js
     module.exports = {
             getOrderdata : async function(orderId){
             //await the response of the fetch call
             let response = await fetch('http://localhost:3245/api/Orders/' + orderId);

             //proceed once the first promise is resolved.
             let data = await response.json();

             //proceed only when the second promise is resolved
             return data;
             }



// file importing the async function - imp.js
const { getOrderdata } = require("./exp.js")
;(async () =>{
    let msg = await getOrderdata()
    console.log(msg)
})();