【问题标题】:How can i use promise returned data in another function later on稍后我如何在另一个函数中使用承诺返回的数据
【发布时间】:2019-06-09 17:59:10
【问题描述】:
async function getOrderdata(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;
}

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

【问题讨论】:

  • 在另一个async函数中使用即可:let x = await GetOrderData(...);
  • const data = await getOrderdata(id)
  • export 该文件中的那个函数,import 到需要它的文件中。
  • 您可以在另一个文件中使用这个async function,就像在另一个文件中使用普通function一样。
  • 请告诉我们另一个文件的代码,您是如何尝试调用 getOrderdata,以及出了什么问题。

标签: javascript asynchronous promise async-await


【解决方案1】:

将函数放在 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)
})();

【讨论】:

  • console.dir(Backend.getOrderdata('0294fa05-d535-4b58-88f8-12ae88404360').then((data) => { return data; }))我使用上面这段代码打印从getOrderdata返回的数据,我得到Object后端是提取api导出的.js文件。
  • @AhmedSalah 在返回数据时尝试使用return JSON.stringify(data,2)
猜你喜欢
  • 2016-08-19
  • 1970-01-01
  • 2017-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多